简介
realm神器作为如今移动端最流行的数据库,是SQLite和CoreData的替代者。可让你不再写SQL语句,其简单,好用
安装
最好使用pods,简单快速
pod 'Realm', '~> 2.2.0'
写入数据
//person
DJPerson *personNew = [DJPerson new];
personNew.name = self.field1.text;
personNew.age = self.field2.text;
personNew.IDCard = [NSString stringWithFormat:@"%zd",self.IDCard.intValue];
personNew.dog = dog;
//save
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm addObject:personNew];
[realm commitWriteTransaction];
删除数据
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
//remove ALL
[realm deleteAllObjects];
//remove one
[realm deleteObject:self.peron1];
[realm commitWriteTransaction];
修改数据
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm addOrUpdateObject:self.peron1];
[realm commitWriteTransaction];
查询数据
RLMResults *persons = [DJPerson allObjects];
for (DJPerson *person in persons)
{
NSLog(@"%@",person);
}
注意点
1一对多时,子对象不能有主键
原因可能,子对象继承了一个抽象的模型类,而抽象类定义了一个主键
2 如果普通对象写入时,因没主键报错,单单加主键后,仍会报错,因为还要数据迁移一下
3RLMArray不支持block快速遍历,forin快速遍历,否则会报错,即使强转为NSArray也没用,
另外NSArray装载RLMObject没事