我有一个系统可以将大量图像保存到plist,除了2个主要问题外,它的效果很好。
首先,当它开始进程时,xcode上的内存转到2G! (完成后放下)
其次,与NSUserdefaults
相比,它需要太长时间(100张图像超过10秒),我告诉它比这慢。
我首先归档数据。
因为拥有如此多的记忆和如此缓慢的储蓄,我做错了什么?
-(void)saveToFileWithData:(NSMutableDictionary*)dic
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:dic];
BOOL sucess=[myData writeToFile:path atomically:YES];
if(sucess)
NSLog(@"saved:%lu",(unsigned long)[myData length]);
else
NSLog(@"failed:%lu",[myData length]);
myData=nil;
}
阅读是这样的:
-(NSMutableDictionary*)readFromFile
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *dic = [[ NSMutableDictionary alloc] init];
NSData *serialized = [NSData dataWithContentsOfFile:path];
//check first if file exist, than if it has content(empty file had 42 bytes-and crashes the archiver)
if ([[NSFileManager defaultManager] fileExistsAtPath:path] && [serialized length]>1000000)
dic = (NSMutableDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:serialized];
serialized=nil;
return dic;
}
将它们用于:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
dic = [self readFromFile];
//change dic
[self saveToFileWithData:dic];
答案 0 :(得分:1)
没有理由将plist从app bundle复制到Documents目录只是为了阅读它。
plist不是一个好的解决方案,在这种情况下它是巨大的将图像单个文件和图像文件名放在plist中。阅读现在的小plist,然后逐个休息图像。单独读取每个文件会占用较少的内存。
但是,你真的想在内存中同时拥有500MB的图像吗?在阅读了图像信息之后,只需根据需要读取图像,或者使用根据使用情况清除图像的缓存。