Ios Realm.io-如何在使用来自服务器的响应数据时使用DefaultPropertyValue?
我知道我们必须使用DefaultPropertyValue。 班级结构:Ios Realm.io-如何在使用来自服务器的响应数据时使用DefaultPropertyValue?,ios,objective-c,realm,Ios,Objective C,Realm,我知道我们必须使用DefaultPropertyValue。 班级结构: @interface Event : RLMObject @property (nonatomic, copy) NSString *roomName; .... - (instancetype)initWithAttributes:(NSDictionary *)attributes; @end @implementation Event + (NSDictionary *)defaultPropertyValue
@interface Event : RLMObject
@property (nonatomic, copy) NSString *roomName;
....
- (instancetype)initWithAttributes:(NSDictionary *)attributes;
@end
@implementation Event
+ (NSDictionary *)defaultPropertyValues {
return @{@"roomName" : @""};
}
- (instancetype)initWithAttributes:(NSDictionary *)attributes {
self = [super init];
if (self) {
self.roomName = [attributes valueForKeyPath:@"room"];
.......
}
return self;
}
“RLMEException”,原因:“没有为“事件”中的属性“roomName”指定值或默认值”
这是因为roomName是由defaultPropertyValues类方法分配的。但一旦从属性字典中解析出来,roomName就变成了零并崩溃。有没有更好的方法来处理这个问题?我不想在[attributes valueForKeyPath:@“room”]上设置if条件您可以通过在实体类(
事件
)上使用Realm的内置方法,而不是自定义初始值设定项,将NSDictionary映射到RLMObjects。如文件所述,当未给出任何值时,这将返回使用默认值:
用于填充对象的对象。这可以是任何键/值编码兼容的对象,也可以是JSON对象,例如从
NSJSONSerialization中的方法,或具有一个对象的NSArray中的方法
每个持久化属性。如果需要,将引发异常
属性不存在且未设置默认值
否则,您需要在自定义初始值设定项中确保不使用nil值覆盖属性。如果您有一个自定义映射,其中属性名称不同,并且您的服务器响应是JSON格式的,那么像这样的对象映射库可能会让您感兴趣
Event *school = [[IVEvent alloc] initWithAttributes:dict];
[realm addObject:school];