Realm.io - 如何在使用来自服务器的响应数据时使用 defaultPropertyValues?

Realm.io - How to use defaultPropertyValues while using response data from server?

我知道我们必须使用 defaultPropertyValues。 Class结构:

@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;
}

...

Event *school = [[IVEvent alloc] initWithAttributes:dict];
[realm addObject:school];

'RLMException',原因:''Event' 中的 属性 'roomName' 没有指定值或默认值'

这是因为 roomName 是通过 defaultPropertyValues class 方法分配的。但是一旦从属性字典中解析出来,roomName 就会变成 nil 并崩溃。有没有更好的方法来处理这个问题?我不想把 if 条件放在 [attributes valueForKeyPath:@"room"]

您可以通过在实体 class (Event) 上使用 Realm 的内置方法 createOrUpdateInRealm:withObject: 而不是自定义初始化程序,将 NSDictionaries 映射到 RLMObjects。如文档所述,当没有给出值时,这将退回到使用默认值:

The object used to populate the object. This can be any key/value coding compliant object, or a JSON object such as those returned from the methods in NSJSONSerialization, or an NSArray with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set.

否则,您需要确保在您的自定义初始化程序中,您不会用 nil 值覆盖属性。如果您有一个自定义映射,其中属性名称不同并且您的服务器响应采用 JSON 格式,那么像 Realm-JSON 这样的对象映射库可能对您来说很有趣。