RLMObject无法用作普通对象

时间:2014-08-22 04:46:30

标签: ios realm

我有一个带有标题的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对象,所以使用它的属性和方法应该没问题,不是吗?

任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:3)

因为Realm对象属性由数据库而不是内存中的ivars支持,所以访问这些属性&#39;不支持ivars。我们目前正在澄清我们的文档以表达这一点:

  

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

因此,要与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:已经这样做了。

相关问题