Clear complete Realm Database

floriankrueger picture floriankrueger · Sep 26, 2014 · Viewed 29.8k times · Source

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

Answer

uɥƃnɐʌuop picture uɥƃnɐʌuop · Sep 26, 2014

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