美文网首页IOS知识积累
Realm使用注意事项OC版

Realm使用注意事项OC版

作者: 黑马饮清泉 | 来源:发表于2018-02-06 16:36 被阅读305次

Realm中文文档:https://realm.io/cn/docs/objc/latest/
优点:安全、稳定、迅速
缺点:不能直接跨线程访问同一对象, 不能分页查询

官方基本使用

1. 打开数据库
// 默认配置
RLMRealm *realm = [RLMRealm defaultRealm];
// 获取 Realm 文件的父目录
NSString *folderPath = realm.configuration.fileURL.URLByDeletingLastPathComponent.path;
// 禁用此目录的文件保护
[[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey: NSFileProtectionNone}
                                 ofItemAtPath:folderPath error:nil];
// 自定义配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 获取预植数据库文件的 URL
config.fileURL = [[NSBundle mainBundle] URLForResource:@"MyBundledData" withExtension:@"realm"];
// 以只读模式打开该文件,这是因为应用的预植数据库是不可写的
config.readOnly = YES;
config.schemaVersion = 1;
// 使用该配置来打开 Realm 数据库
RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil];
2. 内存或文件数据库
// 设置 inMemoryIdentifier 会将 fileURL 置为 nil(反之亦然),创建一个完全在内存中运行的 Realm 数据库 (in-memory Realm),它将不会存储在磁盘当中
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
config.inMemoryIdentifier = @"MyInMemoryRealm";
RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil];
3. 删除 Realm

需要清除缓存或者重置数据库时,需要删除所有数据或者删除Realm文件,避免发生Crash, 以下方法可以使用

// 1. 应用启动时、在打开 Realm 数据库之前完成
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm deleteAllObjects];
[realm commitWriteTransaction];
// 2. 只在显式声明的自动释放池中打开 Realm 数据库,然后在自动释放池后面进行删除
@autoreleasepool {
    // 在这里进行所有的 Realm 操作
}
NSFileManager *manager = [NSFileManager defaultManager];
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
NSArray<NSURL *> *realmFileURLs = @[
    config.fileURL,
    [config.fileURL URLByAppendingPathExtension:@"lock"],
    [config.fileURL URLByAppendingPathExtension:@"note"],
    [config.fileURL URLByAppendingPathExtension:@"management"]
];
for (NSURL *URL in realmFileURLs) {
    NSError *error = nil;
    [manager removeItemAtURL:URL error:&error];
    if (error) {
        // 错误处理
    }
}
3. 对于每个用户建立不同RLMRealmConfiguration,等待合适时机删除
4. 数据模型
#import <Realm/Realm.h>

@class Person;

// 狗狗的数据模型
@interface Dog : RLMObject
@property NSString *name;
@property Person   *owner;
@end
RLM_ARRAY_TYPE(Dog) // 定义 RLMArray<Dog>

// 主人的数据模型
@interface Person : RLMObject
@property NSString             *name;
@property NSDate               *birthdate;
@property RLMArray<Dog *><Dog> *dogs;
@end
RLM_ARRAY_TYPE(Person) // 定义 RLMArray<Person>

// Implementations
@implementation Dog
@end // none needed

@implementation Person
@end // none needed
1) 必需属性
@interface Person : RLMObject
@property NSString *name;
@property NSDate *birthday;
@end

@implementation Person
// 尝试将 name 属性设置为 nil 将会抛出异常
+ (NSArray *)requiredProperties {
    return @[@"name"];
}
@end
2) 主键

声明主键允许对象的查询和更新更加高效, 一旦添加,无法更改

@interface Person : RLMObject
@property NSInteger id;
@property NSString *name;
@end

@implementation Person
+ (NSString *)primaryKey {
    return @"id";
}
@end
3) 索引属性

索引会稍微减慢写入速度,但是使用比较运算符进行查询的速度将会更快(它同样会造成 Realm 文件体积的增大,因为需要存储索引。)当您需要为某些特定情况优化读取性能的时候,那么最好添加索引。

@interface Book : RLMObject
@property float price;
@property NSString *title;
@end

@implementation Book
+ (NSArray *)indexedProperties {
    return @[@"title"];
}
@end
4) 被忽略属性
@interface Person : RLMObject
@property NSInteger tmpID;
@property (readonly) NSString *name; // 只读属性会被自动忽略
@property NSString *firstName;
@property NSString *lastName;
@end

@implementation Person
// 被忽略属性的行为与正常属性完全相同, 这些属性仍能够使用 KVO 进行观察
+ (NSArray *)ignoredProperties {
    return @[@"tmpID"];
}
- (NSString *)name {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}
@end
5) 默认属性值
@interface Book : RLMObject
@property float price;
@property NSString *title;
@end

@implementation Book
+ (NSDictionary *)defaultPropertyValues {
    return @{@"price" : @0, @"title": @""};
}
@end

注意

最近项目中使用到Realm数据库,在无数次Crash中有以下总结:

1. 不要直接跨线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  RLMRealm *realm = [RLMRealm defaultRealm];
  NSString *messageId1 = @"messageId";
  RLMessage *message = [RLMessage objectInRealm:realm forPrimaryKey:messageId1];
  dispatch_async(dispatch_get_main_queue(), ^{
      // Will Crash
       NSString *messageId2 = message.messageId;
  });
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  RLMRealm *realm1 = [RLMRealm defaultRealm];
  NSString *messageId1 = @"messageId";
  RLMessage *message1 = [RLMessage objectInRealm:realm forPrimaryKey:messageId1];
  dispatch_async(dispatch_get_main_queue(), ^{
      // no crash
      RLMRealm *realm2 = [RLMRealm defaultRealm];
      RLMessage *message2 = [RLMessage objectInRealm:realm2 forPrimaryKey:messageId1];
  });
});

构造一个 RLMThreadSafeReference, 传递给目标线程或者队列, RLMThreadSafeReference 对象最多只能够解析一次。如果 RLMThreadSafeReference 解析失败的话,将会导致 Realm 的原始版本被锁死,直到引用被释放为止。因此,RLMThreadSafeReference 的生命周期应该很短

Person *person = [Person new];
person.name = @"Jane";
[realm transactionWithBlock:^{
    [realm addObject:person];
}];
RLMThreadSafeReference *personRef = [RLMThreadSafeReference
    referenceWithThreadConfined:person];

dispatch_async(queue, ^{
    @autoreleasepool {
        RLMRealm *realm = [RLMRealm realmWithConfiguration:realm.configuration
                                                     error:nil];
        Person *person = [realm resolveThreadSafeReference:personRef];
        if (!person) {
            return; // person 被删除
        }
        [realm transactionWithBlock:^{
            person.name = @"Jane Doe";
        }];
    }
});
2. 不要任性的deleteAllObjects

如果数据库正在读写操作,deleteAllObjects会Crash, 解决方案参照上面的"3. 删除 Realm"

3. Tips

https://github.com/bigfish24

相关文章

网友评论

    本文标题:Realm使用注意事项OC版

    本文链接:https://www.haomeiwen.com/subject/jrpgzxtx.html