【问题标题】:NSMutableArray showing (null)/nil?NSMutableArray 显示 (null)/nil?
【发布时间】:2014-05-22 10:18:35
【问题描述】:

你好,我有这样的功能

- (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 显示为其值。

谁能给我解释一下?

【问题讨论】:

  • 检查文件是否存在
  • 另外,你的 plist 是数组还是字典?
  • 我刚刚通过编程方式创建了该 plist

标签: ios objective-c nsmutablearray plist nsmutabledictionary


【解决方案1】:

这一行:

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

将返回 nil 如果:

文件打不开或文件内容无法解析成数组

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

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

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

【讨论】:

  • 你有什么解决办法吗?
  • 已更新。顺便说一句,您应该改进变量名称以遵循编码标准。
  • 你能告诉我一个例子,以便我可以改进这些部分
  • @Akhilrajtr 提供了一个很好的命名示例。变量具有小写首字母并且是驼峰式大小写。类名以第一个大写字母开头。
【解决方案2】:

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

- (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];
        }
        ....
}

【讨论】:

  • 同样的问题仍然存在
猜你喜欢
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多