找个时间,得把各种数据库的原理了解并记录一下。现在先把使用过程中遇到的问题列一下:
1、切记realm数据库支持的类型,使用了数组和字典的要注意了,最好声明一个NSData类型的对应属性,然后使用ignoredProperties忽略数组和字典类型的属性。。在存储时候转化一波!
BOOL, bool, int, NSInteger, long, float, double, CGFloat, NSString, NSDate 和 NSData
2、使用默认数据库并且修改默认数据库的路径时,要先检查修改的文件夹是否存在,否则就会炸掉。
3、新增了一个字段,删除了一个字段,炸掉,提示我,字段变更了,要数据迁移,好吧,整个数据库删掉了,再来。
4、删除报错,Can only delete an object from the Realm it belongs to
这个可能是因为,你模型并不是由数据库查询得到的,所以数据库不能直接删除,建议先用id查询这个对象,然后删除查询到的对象。
5、使用报错,Object has been deleted or invalidated
这个可能是因为,你持有的对象,已经被数据库删除掉了,debug一下打印这个对象,会显示[invalidated object],相当于空对象,再获取吧。
6、直接报错,this class is not key value coding-compliant for the key id.
这个意思是你没有这个id字段,可是我本来就没有这个字段啊,不是很理解,我的处理是重写了valueForUndefinedKey方法,然后将模型的itemID扔出来了。
7、下滑线加属性名可能会获取到空对象,改用self.。
8、报错,RLMException', reason: 'Target table row index out of range
9、报错,'Attempting to create an object of type 'BrTaskConfigModel' with an existing primary key value '<null>'.'
主键为空值,检查一下,最好顺便确保所有的字段都有值。
补充:realm数据的数据迁移
前提:每次数据表结构的改变,都把当前数据库版本加1(int型),[RLMRealm defaultRealm];不要忘了。
1、新增表、新增表字段、删除表、删除表字段,只要数据库版本变化了,realm数据自动迁移,不需要处理。
2、表字段名更改,合并字段,更换字段名名称,可以根据currentVersion和oldSchemaVersion判断并进行相应的迁移。
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
config.fileURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/RealmDB.realm", dbPath]];
config.readOnly = NO;
int currentVersion = 4;
config.schemaVersion = currentVersion;
config.migrationBlock = ^(RLMMigration *migration , uint64_t oldSchemaVersion) {
// 这里是设置数据迁移的block
[migration enumerateObjects:[RealmObject className]
block:^(RLMObject *oldObject, RLMObject *newObject) {
//合并字段
newObject[@"name"] = [NSString stringWithFormat:@"%@-%@", oldObject[@"age"], oldObject[@"address"]];
//赋值
newObject[@"age"] = @"14";
}];
//字段重命名
[migration renamePropertyForClass:RealmObject.className oldName:@"yearsSinceBirth" newName:@"age"];
};
// 将这个配置应用到默认的 Realm 数据库当中
[RLMRealmConfiguration setDefaultConfiguration:config];
[RLMRealm defaultRealm];