Realm可空属性,默认值,忽略属性,通知
2017-07-08 本文已影响45人
爱做梦的星星
文章类型: 学习笔记
Realm文章链接:
Realm可空属性
@interface student : RLMObject
@property NSString *name;
@property int number;
@property float weight;
@property NSString *address;
@end
// This protocol enables typed collections. i.e.:
// RLMArray<student *><student>
RLM_ARRAY_TYPE(student)
//测试
student *stu = [[student alloc] init];
stu.number = 22;
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
[realm addObject:stu];
}];
结果
![image_1bkh98c2cac31l801luojunku49.png-30.3kB](http://static.zybuluo.com/liuxingxing/4mfoe7i0r6022yxmp6y8aur0/image_1bkh98c2cac31l801luojunku49.png)
未约束可以有空值.
Realm非空值
@interface student : RLMObject
@property NSString *name;
@property int number;
@property float weight;
@property NSString *address;
@end
// This protocol enables typed collections. i.e.:
// RLMArray<student *><student>
RLM_ARRAY_TYPE(student)
//要强调非空值需要在.m中实现方法
//约束`address`字段不能为空
+ (NSArray<NSString *> *)requiredProperties {
return @[@"address"];
}
默认值
@interface student : RLMObject
@property NSString *name;
@property int number;
@property float weight;
@property NSString *address;
@end
// This protocol enables typed collections. i.e.:
// RLMArray<student *><student>
RLM_ARRAY_TYPE(student)
//要强调非空值需要在.m中实现方法
//给`address`字段增加默认值
+ (NSDictionary *)defaultPropertyValues {
return @{@"address":@"110"};
}
忽略属性(前文已经提到了)
//想忽略一个属性不让他存储
//1.加readonly
@property (readonly)NSString *name;
//2.实现中定方法
+ (NSArray<NSString *> *)ignoredProperties {
return @[@"name"];
}
//一般开发中使用到时间
//存储时间,同时多存一个时间格式化后的字符串
@property NSTimeInterval time;
@property (readonly)NSString *timeFormat;
//重写time的set方法中转化为需要的时间样式赋值timeFormat,这样取得时候直接取格式化后的就行了
//这种时间格式化后的属性又被成为弱业务逻辑
Realm通知
//Realm中存在通知,当用户修改数据库的时候会触发通知
//注:必须用强引用持有通知token
@property (nonatomic , strong)RLMNotificationToken *token;
//设置通知
RLMRealm *realm = [RLMRealm defaultRealm];
self.token = [realm addNotificationBlock:^(RLMNotification _Nonnull notification, RLMRealm * _Nonnull realm) {
NSLog(@"数据库发生改变了");
}];
//关闭通知
[self.token stop];
//结果集也可以时时监听,可以拿到改变的数值
//第一次RLMCollectionChange为改变的值,自己试试
@property (nonatomic , strong)RLMNotificationToken *token2;
RLMResults *result = [student allObjects];
self.token2 =[result addNotificationBlock:^(RLMResults * _Nullable results, RLMCollectionChange * _Nullable change, NSError * _Nullable error) {
NSLog(@"结果集发生改变了");
}];