iOS 持久化,读取本地文件数据导致程序崩溃

新手上路,请多包涵

不废话,直接贴代码:

@property NSMutableArray *NewItems;

//初始化 本地存储文件
NSString* path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
self.storeFilename = [path stringByAppendingPathComponent:@"storefile.plist"];

//存储数据
[self.NewItems addObject:item];
[self.NewItems writeToFile:self.storeFilename atomically:YES];

//从本地文件 读取数据
NSArray* storedItems = [NSArray arrayWithContentsOfFile:self.storeFilename];
[self.NewItems addObjectsFromArray:storedItems];

初始化完成后,从本地文件读取数据,空的时候正常。增加并存入数据后,下次启动,读取数据时程序崩溃。显示:
  

libc++abi.dylib: terminating with uncaught exception of type NSException

阅读 3.3k
1 个回答

If the array’s contents are all property list objects (NSString,
NSData, NSArray, or NSDictionary objects), the file written by this
method can be used to initialize a new array with the class method
arrayWithContentsOfFile: or the instance method
initWithContentsOfFile:. This method recursively validates that all
the contained objects are property list objects before writing out the
file, and returns NO if all the objects are not property list objects,
since the resultant file would not be a valid property list.

自定有类对象实例item不能用这种方法进行存储, 可以通过NSKeyedArchiver转成NSdata,然后才能使用writeToFile:方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题