Clear complete Realm Database

后端 未结 6 2016
半阙折子戏
半阙折子戏 2020-12-24 11:45

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 de

相关标签:
6条回答
  • 2020-12-24 11:52

    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")
    }
    
    0 讨论(0)
  • 2020-12-24 11:53

    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.

    0 讨论(0)
  • 2020-12-24 12:01

    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"
    }
    
    0 讨论(0)
  • 2020-12-24 12:06

    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];
            }
        }
    }];
    
    0 讨论(0)
  • 2020-12-24 12:06

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

    0 讨论(0)
  • 2020-12-24 12:14

    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) {
    
            }];
    
    0 讨论(0)
提交回复
热议问题