Domanda

I am persisting large objects on disk which answer to the NSCoding Protocol. I would like to lazy load the object's instance variables on demand and am wondering if it is possible to always read the object from disk (testing will not necessarily answer this question). I can not use Core Data in my application so that is not an option.

A use case scenario

For instance

@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
È stato utile?

Soluzione

Rather than trying to abuse the system you should tweak your design slightly to better support your requirements. Instead of archiving the whole object as one item and including the image, look at saving the images as individual files and archiving the object with paths to those images. Now, when the object is recreated you can properly and fully reload the instance and then you can lazy load the images from their paths when required.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top