1

私はProductヘッダーを持つモデルを持っています:

@interface Product : RLMObject <NSCopying,NSCoding>
{
}
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *thumbnailURL;
@property (nonatomic, strong) UIImage *thumbnail;

-(id)initWithInfo:(NSDictionary*)dictionary;
-(UIImage*)getThumbnail;

と実装:

@implementation Product

-(id)initWithInfo:(NSDictionary*)dictionary
{
    self = [self init];
    if (self) {
        _title = dictionary[@"title"];
        _thumbnailURL = dictionary[@"thumbnailURL"];
        _thumbnail = [self getThumbnail];
    }

    return self;
}

-(UIImage*)getThumbnail
{
    if (_thumbnail) {
        return _thumbnail;
    }

    //load image from cache
    return [self loadImageFromCache];
}

今、Productオブジェクトを作成してに挿入しようとするとRealm、常に例外が発生します

[RLMStandalone_Product getThumbnail]: unrecognized selector sent to instance 0xcd848f0'

今、私は削除_thumbnail = [self getThumbnail];し、それは正常に動作します. しかし、その後、別の例外が発生します

[RLMStandalone_Product title]: unrecognized selector sent to instance 0xd06d5f0'

ビューをリロードすると。メイン スレッドでオブジェクトを作成Productしたので、そのプロパティとメソッドを使用しても問題ないはずです。

アドバイスをいただければ幸いです。

4

1 に答える 1

3

Realm オブジェクトのプロパティはメモリ内 ivar ではなくデータベースによってサポートされるため、これらのプロパティの ivar へのアクセスはサポートされていません。現在、これを伝えるためにドキュメントを明確にしています。

が作成または取得されたスレッドでのみオブジェクトを使用できることに注意してください。永続化されたプロパティに対して ivar に直接アクセスしてはならず、永続化されたプロパティのゲッターとセッターをオーバーライドすることはできません。

Realm を使用するには、モデルは次のようになります。

@interface Product : RLMObject

@property NSString *title;
@property NSString *thumbnailURL;
@property (nonatomic, strong) UIImage *thumbnail;

@end

@implementation Product

-(UIImage*)thumbnail
{
    if (!_thumbnail) {
        _thumbnail = [self loadImageFromCache];
    }
    return _thumbnail;
}

-(UIImage*)loadImageFromCache
{
    // Load image from cache
    return nil;
}

+(NSArray*)ignoredProperties
{
    // Must ignore thumbnail because Realm can't persist UIImage properties
    return @[@"thumbnail"];
}

@end

このモデルの使用法は次のようになります。

[[RLMRealm defaultRealm] transactionWithBlock:^{
    // createInDefaultRealmWithObject: will populate object keypaths from NSDictionary keys and values
    // i.e. title and thumbnailURL
    [Product createInDefaultRealmWithObject:@{@"title": @"a", @"thumbnailURL": @"http://example.com/image.jpg"}];
}];

NSLog(@"first product's image: %@", [(Product *)[[Product allObjects] firstObject] thumbnail]);

すでにこれを行っているinitWithInfoため、必要ではないことに注意してください。RLMObjectinitWithObject:createInDefaultRealmWithObject:

于 2014-08-22T18:50:31.493 に答える