gpt4 book ai didi

ios - 是否可以延迟加载符合 nscoding 协议(protocol)的对象

转载 作者:行者123 更新时间:2023-11-29 10:55:34 24 4
gpt4 key购买 nike

我在磁盘上保存响应 NSCoding 协议(protocol)的大型对象。我想按需延迟加载对象的实例变量,并且想知道是否可以始终从磁盘读取对象(测试不一定能回答这个问题)。我不能在我的应用程序中使用核心数据,所以这不是一个选项。

一个用例场景

例如

@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

最佳答案

与其尝试滥用系统,不如略微调整您的设计以更好地支持您的要求。与其将整个对象作为一个项目存档并包括图像,不如考虑将图像保存为单独的文件并使用这些图像的路径存档对象。现在,当对象被重新创建时,您可以正确地完全重新加载实例,然后您可以在需要时从它们的路径延迟加载图像。

关于ios - 是否可以延迟加载符合 nscoding 协议(protocol)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18574086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com