先从数据库最基本的增删查改来看realm怎么用
// 增
- (void)addObject {
//添加数据
Model *model = [self loadData];
//将数据加入到数据库中
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
[realm addObject:model];
}];
NSLog(@"results: %@",[Model allObjects]);
}
// 删
- (void)deleteObject {
//获取OrderModel所有数据
RLMResults *results = [Model allObjects];
NSLog(@"results: %@",results);
//添加数据
Model *model =nil;
if(results.count) model = [results firstObject];
//将数据加入到数据库中
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
[realm deleteObject:model];
[realm deleteAllObjects];
}];
NSLog(@"results: %@",results);
}
// 查
- (void)queryObject {
//查询字符串时需要加上''号
//基本用法查询字符串
//Name对应name的数组
RLMResults *Results = [Model objectsWithPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"Name == '%@',name"]]];
//关于Model的检索
//objectId大于2进行查询
RLMResults *results = [Model objectsWhere:@"objectId > 2"];
NSLog(@"results: %@",results);
//objectId大于2小于6进行查询
// RLMResults *regionResults = [Model objectsWhere:@"objectId > 2 AND objectId < 6"];
RLMResults *regionResults = [Model objectsWhere:@"objectId BETWEEN{2,6}"];
NSLog(@"results: %@",regionResults);
//关于Model的检索
//检索Name含有l的Model(CONTAINS 包含)([c]是不区分大小写)
RLMResults *results = [Model objectsWhere:@"Name CONTAINS[c] 'l'"];
NSLog(@"results: %@", results);
//检索Name为lj并且rlmModelArray的个数大于3的Model
RLMResults *mergeResults = [[Model objectsWhere:@"Name == 'lj'"] objectsWhere:@"rlmModelArray.@count < 3"];
NSLog(@"results: %@",mergeResults);
}
// 改
- (void)modifyObject {
//获取Model所有数据
RLMResults *results = [Model allObjects];
NSLog(@"results: %@",results);
//添加数据
Model *model = nil;
if (results.count) model = [results firstObject];
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
model.time = [NSDate date];
}];
NSLog(@"results: %@",results);
//批量修改
//获取Model所有数据
RLMResults *modelResults = [Model allObjects];
NSLog(@"results: %@", modelResults);
[realm transactionWithBlock:^{
[modelResults setValue:@(123) forKey:@"objectId"];
}];
NSLog(@"results: %@", modelResults);
}
}
realm其余的关系与属性
// 主键(唯一性)(查询更快)
+ (NSString*)primaryKey {
return @"modelId";
}
// 索引属性支持(NSString,NSNumber,NSDate)(可以比一般属性更快的查询)
+ (NSArray *)indexedProperties {
return @[@"modelAttribute"];
}
// 默认属性(realm基本属性是不可以传nil的,可以在这里给个默认值0)
+ (NSDictionary*)defaultPropertyValues {
return @{@"objectId":@(0)};
}
// 反向关系
+ (NSDictionary*)linkingObjectsProperties {
return @{@"model" : [RLMPropertyDescriptor descriptorWithClass:Model.class propertyName:@"rlmModelArray"]};
}
// 忽略属性
+ (NSArray*)ignoredProperties {
return @[@"ignoreName"];
}