清除完整的Realm数据库 [英] Clear complete Realm Database

查看:1414
本文介绍了清除完整的Realm数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用领域(目前为0.85.0),我的应用程序使用数据库来存储用户特定的数据,例如当前用户的联系人。当用户决定退出时,我需要删除关于用户的每一点信息,在我看来,最明显,简单和干净的东西将是擦除整个领域。不幸的是,Cocoa lib没有提供这种功能。

I'm playing around with realm (currently 0.85.0) and my application uses the database to store user-specific data such as the contacts of the current user. When the user decides to log out I need to remove every single bit of information about the user and the most obvious, simple and clean thing in my opinion would be to wipe the complete realm. Unfortunately, the Cocoa lib doesn't provide that functionality.

目前,我坚持使用以下

RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm deleteObjects:[MyRealmClass1 allObjectsInRealm:realm]];
[realm deleteObjects:[MyRealmClass2 allObjectsInRealm:realm]];
[realm deleteObjects:[MyRealmClass3 allObjectsInRealm:realm]];
[realm commitWriteTransaction];

任何更好的创意?

谢谢

推荐答案

更新:

自发布以来,添加了一个删除所有对象的新方法(如jpsim已经提到的):

Since posting, a new method has been added to delete all objects (as jpsim has already mentioned):

// Obj-C
[realm beginWriteTransaction];
[realm deleteAllObjects];
[realm commitWriteTransaction];


// Swift
try! realm.write {
  realm.deleteAll()
}

请注意这些方法不会改变数据结构;他们只删除现有记录。如果您希望在不编写迁移的情况下更改领域模型属性(即,正如您在开发中所做的那样),下面的旧解决方案可能仍然有用。

Note that these methods will not alter the data structure; they only delete the existing records. If you are looking to alter the realm model properties without writing a migration (i.e., as you might do in development) the old solution below may still be useful.

原始答案:

你可以简单地删除领域文件本身,就像他们在用于存储REST响应的示例代码

You could simply delete the realm file itself, as they do in their sample code for storing a REST response:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //...

    // Ensure we start with an empty database
    [[NSFileManager defaultManager] removeItemAtPath:[RLMRealm defaultRealmPath] error:nil];

    //...
}






关于您的评论的更新:

如果您需要确保不再使用领域数据库,你可以使用领域的通知。如果你在每次写入之前增加一个 openWrites 计数器,那么你可以在每次写入完成时运行一个块:

If you need to be sure that the realm database is no longer in use, you could put realm's notifications to use. If you were to increment an openWrites counter before each write, then you could run a block when each write completes:

self.notificationToken = [realm addNotificationBlock:^(NSString *notification, RLMRealm * realm) {
    if([notification isEqualToString:RLMRealmDidChangeNotification]) {
        self.openWrites = self.openWrites - 1;

        if(!self.openWrites && self.isUserLoggedOut) {
            [[NSFileManager defaultManager] removeItemAtPath:[RLMRealm defaultRealmPath] error:nil];
        }
    }
}];

这篇关于清除完整的Realm数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆