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
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:方法。
这篇关于iOS 持久化,读取本地文件数据导致程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!