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 对象属性是由数据库而不是内存中的 ivars 支持的,所以不支持访问这些属性的 ivars。我们目前正在澄清我们的文档以传达这一点:

请注意,您只能在创建或获取的线程上使用对象,不应直接访问任何持久属性的 ivars,并且不能覆盖持久属性的 getter 和 setter。

因此,要使用 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是不必要的,因为RLMObject已经initWithObject:并且createInDefaultRealmWithObject:已经这样做了。

于 2014-08-22T18:50:31.493 回答