Clear complete Realm Database

2020-02-17 08:40发布

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

标签: ios realm
6条回答
Anthone
2楼-- · 2020-02-17 09:07

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()

查看更多
在下西门庆
3楼-- · 2020-02-17 09:11

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")
}
查看更多
姐就是有狂的资本
4楼-- · 2020-02-17 09:12

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];
        }
    }
}];
查看更多
▲ chillily
5楼-- · 2020-02-17 09:17

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"
}
查看更多
来,给爷笑一个
6楼-- · 2020-02-17 09:20

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.

查看更多
姐就是有狂的资本
7楼-- · 2020-02-17 09:31

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) {

        }];
查看更多
登录 后发表回答