【ios】NSMutableArray initWithContentOfFile 得到nil后无法进行addObject的问题
問題
看如下代碼,我們希望從沙盒的plist文件中解析出內(nèi)容,賦值給一個可變數(shù)組。并且針對這個可變數(shù)組添加新的對象。
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);執(zhí)行代碼后,我們發(fā)現(xiàn)結(jié)果為
null{content = "add\U4eb2\U4eb2";date = "2017-09-27 16:46:00"; }null出現(xiàn)一個很有意思的問題,很明顯self.plistPath所指向的文件是空的,所以解析失敗,無法正確賦值給array,導(dǎo)致后面的addObject也失敗了。
分析
上網(wǎng)查詢了下資料
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如果不能被打開或者解析為一個可變數(shù)組的時候,就返回nil。
看來對于nil調(diào)用addObject的方式,依然結(jié)果會是nil。
解決方案
我們調(diào)整代碼如下,加入一個類型初始化。
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];進行上面修改后,就沒有問題了。
總結(jié)
以上是生活随笔為你收集整理的【ios】NSMutableArray initWithContentOfFile 得到nil后无法进行addObject的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决 webstrom sass 注释中
- 下一篇: oracle之 安装 11G RAC 报