我在磁盘上持有大对象,它们符合NSCoding协议。我想根据需要延迟加载对象的实例变量,我想知道是否有可能始终从磁盘读取对象(测试不一定会回答这个问题)。我不能在我的应用程序中使用Core Data,因此这不是一个选项。
用例场景
例如
@interface AClassWhichCreatesObjectsWithLotsOfData <NSCoding>
-(UIImage *)getImage1; // could be a huge image
-(UIImage *)getImage2; // another huge image
...
@end
@implementation AClassWhichCreatesObjectsWithLotsOfData
// serializing the object
-(void)encodeWithCoder:(NSCoder *)aCoder
{
//encode object to write to disk
}
// would like to store the "aDecoder" and load the images lazilly
-(id)initWithCoder:(NSCoder *)aDecoder
{
// Can I Lazy Load this objects data according to aDecoder ?
self.myDecoder = aDecoder //store the decoder - will aDecoder ever invalidate?
}
-(UIImage *)getImage1 // lazy load the image
{
if (self.myDecoder != nil && self.image1 == nil )
{
return [self.myDecoder decodeObjectForKey:@"image1"];
} else {
return self.image1;
}
}
@end
// thousands of objects are stored in this collection
@interface DiskBackedDictionary : NSObject // if this was in memory app would crash because of memory usage
-(void)setObject:(id<NSCoding>)object forKey:(NSString *)aKey
-(id)objectForKey:(NSString *)key;
@end
@implementation DiskBackedDictionary
-(void)setObject(id<NSCoding>)object forKey:(NSString *)akey
{
// write the object to disk according to aKey
}
-(id)objectForKey:(NSString *)aKey
{
// return a lazy loaded object according to a key
}
@end
答案 0 :(得分:2)
您应该稍微调整一下设计,以便更好地支持您的要求,而不是试图滥用系统。不是将整个对象存档为一个项目并包含图像,而是将图像保存为单个文件,并使用指向这些图像的路径存档对象。现在,当重新创建对象时,您可以正确地重新加载实例,然后在需要时可以从路径中延迟加载图像。