【发布时间】:2012-03-21 08:49:37
【问题描述】:
我正在使用 NSCoding 来管理具有几个不同字段的自定义对象,其中一个是图像。我只针对 iOS 5.0+ 并已切换到 ARC。我一切正常,但专注于性能——我还没有看到过这样的问题,所以就这样吧:
我将 UIImage 转换为 NSData 并将其添加到主 NSCoding 文件(如果重要,则为 plist)以存储在磁盘上。如果有多个图像,图像名称将变为连续的(例如 image1、image2、image3。)然后我在 UITableView(作为调整大小的缩略图)和详细视图中都使用该图像。不利的一面是 plist 的大小会膨胀,这意味着当我使用它时初始加载时间很慢,因为它一次加载所有 NSData。
消除此问题并一次只强制加载一张图片的最佳方法是什么?
我的想法:
我将 NSData 写入磁盘,将一个数组添加到 plist,并且只将每个图像的文件名的引用添加到数组中。我想我会在指定位置引用图像文件名,在磁盘上找到它并使用它?
欢迎提出任何想法。与其他任何事情相比,我更停留在概念实现上,而且有趣的是,这不是一个经常讨论的话题。
谢谢,
编辑:
按照下面的要求,这是一个拍摄图像并将其转换为 NSData 的示例:
UIImage *originalImage;
NSData *imageData = UIImagePNGRepresentation(originalImage);
//I save it all to the app's document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//I am using the images in a tableView and thus found it easiest to append the row number to each image filename.
//'y' below is just an integer that corresponds to the number of items in the master array
NSString *fileName = [NSString stringWithFormat:@"image%d.png",y];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:fileName];
[imageData writeToFile:documentsDirectory atomically:YES];
// NSLog(@"The filename is %@", fileName);
//newObject is an instance of my NSCoding object
[newObject setImageName: fileName];
【问题讨论】:
-
是的,您将图像存储为单独的文件并通过文件名引用它们的想法正是我要做的。如果记录的数量变得足够大,以至于加载所有非图像字段开始需要很长时间,我可能会切换到 Core Data 来获取非图像数据。
-
您有将 UIImage 序列化为 NSData 的快速代码示例吗?它对我正在从事的项目很有用,毫无疑问对其他人也有用。
标签: iphone ios uiimage nsdata nscoding