我在磁盘上保留了响应 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