NSMutableArray显示(null)/ nil?

时间:2014-05-22 10:18:36

标签: ios objective-c nsmutablearray plist nsmutabledictionary

嗨我有这样的功能

- (void)save{
        NSLog(@" %@ %@ %@ %@",AppAddressLine,AppCustomerName,AppPhoneNumber,AppPriceTier);

        paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory = [paths objectAtIndex:0];
        path = [documentsDirectory stringByAppendingPathComponent:@"NewInAppCustomer.plist"];
        NSMutableArray *MainRoot=[[NSMutableArray alloc]initWithContentsOfFile:path];
        NSMutableDictionary *ContentDictionary=[[NSMutableDictionary alloc]init];
        [ContentDictionary setValue:AppCustomerName  forKey:@"CustomerName"];
        [ContentDictionary setValue:AppAddressLine forKey:@"CustomerAddress"];
        [ContentDictionary setValue:AppPhoneNumber forKey:@"CustomerPhoneNumber"];
        [ContentDictionary setValue:AppPriceTier forKey:@"CustomerPriceTier"];
        [MainRoot addObject:ContentDictionary];
        [MainRoot writeToFile:path atomically:YES];
        NSLog(@"%@",MainRoot);

}

打印时
NSLog(@" %@ %@ %@ %@",AppAddressLine,AppCustomerName,AppPhoneNumber,AppPriceTier);

显示正确的值,

但这一行

NSLog(@"%@",MainRoot);

显示nil作为其值。

有人可以向我解释一下吗?

2 个答案:

答案 0 :(得分:2)

这一行:

NSMutableArray *MainRoot=[[NSMutableArray alloc]initWithContentsOfFile:path];

将返回nil if:

  

无法打开文件或无法将文件内容解析为数组

所以你有一个不存在或无效的文件。

因此,您应该确保在此代码运行之前创建文件,或者更好的是,检查结果并在需要时创建一个新的空数组。

if (MainRoot == nil) MainRoot = [NSMutableArray array];

答案 1 :(得分:1)

试试这个,如果文件不存在则创建该文件然后写入

- (void)save{
        NSLog(@" %@ %@ %@ %@",AppAddressLine,AppCustomerName,AppPhoneNumber,AppPriceTier);

        paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory = [paths objectAtIndex:0];
        path = [documentsDirectory stringByAppendingPathComponent:@"NewInAppCustomer.plist"];
        NSMutableArray *mainRoot;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:path]) {

             [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
             mainRoot = [[NSMutableArray alloc] init];
        } else {
             mainRoot = [[NSMutableArray alloc] initWithContentsOfFile:path];
        }
        ....
}