Should I define the primary key for each entity in Realm?

后端 未结 2 1012
夕颜
夕颜 2021-02-02 12:53

I have noticed that setting PK is not obligatory in Realm and simply can be omitted. But in documentation is stated that:

Indexes are created automatical

2条回答
  •  春和景丽
    2021-02-02 13:25

    The horse has been beaten to death already, but I couldn't help but reference the Realm code which throws an exception if a Realm Object is created or updated without having a primary key.

    + (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value {
        // verify primary key
        RLMObjectSchema *schema = [self sharedSchema];
        if (!schema.primaryKeyProperty) {
            NSString *reason = [NSString stringWithFormat:@"'%@' does not have a primary key and can not be updated", schema.className];
            @throw [NSException exceptionWithName:@"RLMExecption" reason:reason userInfo:nil];
        }
        return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, true);
    }
    

提交回复
热议问题