日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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];

進行上面修改后,就沒有問題了。

總結

以上是生活随笔為你收集整理的【ios】NSMutableArray initWithContentOfFile 得到nil后无法进行addObject的问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。