我有一个系统可以将大量图像保存到 plist 中,效果很好,除了 2 个主要问题。
首先,当它启动进程时,xcode上的内存变为2G!(完成后向下(其次,它花费的时间太长(10 张图像需要 100+ 秒(与 NSUserdefaults
相比,我告诉它比这慢。
我首先存档数据。
我做错了什么,拥有这么多内存而保存如此缓慢?
-(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];
没有理由将 plist 从应用程序包复制到文档目录只是为了阅读它。
plist不是一个好的解决方案,在这种情况下,它很大 将图像单个文件和图像文件名放在plist中。阅读现在的小列表,然后一个接一个地休息图像。单独读取每个文件使用较少的内存量。
但是,您真的希望一次在内存中存储 500MB 的图像吗?读取图像信息列表后,只需根据需要读取图像,也许使用根据使用情况清除图像的缓存。