1

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

1 回答 1

2

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

于 2013-09-02T13:40:07.013 回答