gpt4 book ai didi

ios - RLMObject 无法用作普通对象

转载 作者:行者123 更新时间:2023-12-01 18:57:45 25 4
gpt4 key购买 nike

我有一个 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];它工作正常。但后来我得到另一个异常(exception)
[RLMStandalone_Product title]: unrecognized selector sent to instance 0xd06d5f0'

当我重新加载我的 View 时。我创建了我的 Product主线程中的对象,所以使用它的属性和方法应该没问题,不是吗?

任何建议将被认真考虑!

最佳答案

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

Please note that you can only use an object on the thread from which is was created or obtained, ivars shouldn't be accessed directly for any persisted properties, and that getters and setters for persisted properties cannot be overridden.



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

关于ios - RLMObject 无法用作普通对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25439713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com