【ios】NSMutableArray initWithContentOfFile 得到nil后无法进行addObject的问题

问题

看如下代码,我们希望从沙盒的plist文件中解析出内容,赋值给一个可变数组。并且针对这个可变数组添加新的对象。

NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:self.plistFilePath];
NSLog(@"%@",array);

NSString *date = [self.dateFormatter stringFromDate:model.date];
NSDictionary *dict = @{@"date":date, @"content":model.content};
NSLog(@"%@",dict);

[array addObject:dict];
NSLog(@"%@",array);

执行代码后,我们发现结果为

null

{
    content = "add\U4eb2\U4eb2";
    date = "2017-09-27 16:46:00";
}

null

出现一个很有意思的问题,很明显self.plistPath所指向的文件是空的,所以解析失败,无法正确赋值给array,导致后面的addObject也失败了。

分析

上网查询了下资料

Return Value
A mutable array initialized to contain the contents of the file specified by aPath or nil if the file can’t be opened or the contents of the file can’t be parsed into a mutable array. The returned object must be different than the original receiver.

initWithContentsOfFile:苹果文档

重点就是if the file can’t be opened or the contents of the file can’t be parsed into a mutable array如果不能被打开或者解析为一个可变数组的时候,就返回nil

看来对于nil调用addObject的方式,依然结果会是nil

解决方案

我们调整代码如下,加入一个类型初始化。

NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:self.plistFilePath];

// 在这里,我们通过判断如果array为nil,也就是plist文件为空的时候进行初始化。
if(!array) {
   array = [NSMutableArray new];
}

NSString *date = [self.dateFormatter stringFromDate:model.date];
NSDictionary *dict = @{@"date":date, @"content":model.content};

[array addObject:dict];

进行上面修改后,就没有问题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值