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

发布时间:2019-06-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【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 = "addU4eb2U4eb2";
    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];

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

脚本宝典总结

以上是脚本宝典为你收集整理的【ios】NSMutableArray initWithContentOfFile 得到nil后无法进行addObject的问题全部内容,希望文章能够帮你解决【ios】NSMutableArray initWithContentOfFile 得到nil后无法进行addObject的问题所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。