Clear complete Realm Database

无人久伴 提交于 2019-12-18 10:49:09

问题


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.

Currently, I'm stuck with the following

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

any better ideas?

thanks


回答1:


Update:

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.

Original Answer:

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];

    //...
}

Update regarding your comment:

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];
        }
    }
}];



回答2:


RealmSwift: Simple reset using a flag

Tried the above answers, but posting one more simple way to delete the realm file instead of migrating:

Realm.Configuration.defaultConfiguration.deleteRealmIfMigrationNeeded = true

This simply sets a flag so that Realm can delete the existing file rather than crash on try! Realm()

Instead of manually deleting the file

Thought that was simpler than the Swift version of the answer above:

guard let path = Realm.Configuration.defaultConfiguration.fileURL?.absoluteString else {
    fatalError("no realm path")
}

do {
    try NSFileManager().removeItemAtPath(path)
} catch {
    fatalError("couldn't remove at path")
}



回答3:


As of realm 0.87.0, it's now possible to delete all realm contents by calling [[RLMRealm defaultRealm] deleteAllObjects] from a write transaction.

From Swift, it looks like this: RLMRealm.defaultRealm().deleteAllObjects()




回答4:


In case someone stumbles on this question looking for a way to do this in Swift, this is just DonamiteIsTnt's answer rewritten. I've added this function to a custom utility class so I can do MyAppUtilities.purgeRealm() during testing & debugging

func purgeRealm() {
    NSFileManager.defaultManager().removeItemAtPath(RLMRealm.defaultRealmPath(), error: nil)
}

Note: If you find yourself in need of clearing data you might just check out Realm's new realm.addOrUpdateObject() feature which allows you to replace existing data by its primary key with the new data. This way you're not continually adding new data. Just replacing "old" data. If you do use addOrUpdateObject() make sure you override your model's primaryKey class function so Realm knows which property is your primary key. In Swift, for example:

override class func primaryKey() -> String {
    return "_id"
}



回答5:


I ran into this fun little issue. So instead i queried the schema version directly before running the schemamigration.

NSError *error = NULL;
NSUInteger currentSchemaVersion = [RLMRealm schemaVersionAtPath:[RLMRealm defaultRealmPath] error:&error];
if (currentSchemaVersion == RLMNotVersioned) {
    // new db, skip

} else if (currentSchemaVersion < 26) {
    // kill local db
    [[NSFileManager defaultManager] removeItemAtPath:[RLMRealm defaultRealmPath] error:&error];
    if (error) {
        MRLogError(error);
    }

} else if (error) {
    // for good measure...
    MRLogError(error);
}

// perform realm migration
[RLMRealm setSchemaVersion:26
            forRealmAtPath:[RLMRealm defaultRealmPath]
        withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {

        }];



回答6:


You can also go to the location where your realm file is stored, delete that file from there and next time when you open realm after running app, you will see the empty realm database in browser.



来源:https://stackoverflow.com/questions/26067193/clear-complete-realm-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!