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

システムを悪用しようとするのではなく、要件をより適切にサポートするように設計を微調整する必要があります。画像を含むオブジェクト全体を 1 つのアイテムとしてアーカイブする代わりに、画像を個別のファイルとして保存し、それらの画像へのパスを使用してオブジェクトをアーカイブすることを検討してください。これで、オブジェクトが再作成されたら、インスタンスを適切かつ完全にリロードし、必要に応じてパスからイメージを遅延ロードできます。

于 2013-09-02T13:40:07.013 に答える