Clear complete Realm Database2019 Community Moderator ElectionHow to completely destroy and recreate a Realm databaseRealm objects intermittently not being present when app launchesiOS background fetch time limit crashHow to find my realm file?This action could not be completed. Try Again (-22421)Reusing snapshots of Realm databasesHow to use Realm “live” objects and keep database layer decoupled from other layers(business, UI, etc)?Realm objects intermittently not being present when app launchesRealm file size in iOS appRealm Swift inverse relationships many-to-manyRealm thread safe object with singletonRealm in installed app, but not Instant App?

Does splitting a potentially monolithic application into several smaller ones help prevent bugs?

Can anyone tell me why this program fails?

Replacing Windows 7 security updates with anti-virus?

When do we add an hyphen (-) to a complex adjective word?

I need to drive a 7/16" nut but am unsure how to use the socket I bought for my screwdriver

What is the greatest age difference between a married couple in Tanach?

Be in awe of my brilliance!

Latest web browser compatible with Windows 98

Is having access to past exams cheating and, if yes, could it be proven just by a good grade?

Making a sword in the stone, in a medieval world without magic

What is IP squat space

Do I need life insurance if I can cover my own funeral costs?

Calculus II Professor will not accept my correct integral evaluation that uses a different method, should I bring this up further?

Is a lawful good "antagonist" effective?

PlotLabels with equations not expressions

Sword in the Stone story where the sword was held in place by electromagnets

How do anti-virus programs start at Windows boot?

Does the statement `int val = (++i > ++j) ? ++i : ++j;` invoke undefined behavior?

Why must traveling waves have the same amplitude to form a standing wave?

Know when to turn notes upside-down(eighth notes, sixteen notes, etc.)

What options are left, if Britain cannot decide?

Happy pi day, everyone!

How to simplify this time periods definition interface?

How to deal with a cynical class?



Clear complete Realm Database



2019 Community Moderator ElectionHow to completely destroy and recreate a Realm databaseRealm objects intermittently not being present when app launchesiOS background fetch time limit crashHow to find my realm file?This action could not be completed. Try Again (-22421)Reusing snapshots of Realm databasesHow to use Realm “live” objects and keep database layer decoupled from other layers(business, UI, etc)?Realm objects intermittently not being present when app launchesRealm file size in iOS appRealm Swift inverse relationships many-to-manyRealm thread safe object with singletonRealm in installed app, but not Instant App?










37















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










share|improve this question




























    37















    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










    share|improve this question


























      37












      37








      37


      7






      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










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 23 '15 at 20:25









      Michael Alan Huff

      3,21232142




      3,21232142










      asked Sep 26 '14 at 19:44









      floriankruegerfloriankrueger

      1,63021322




      1,63021322






















          6 Answers
          6






          active

          oldest

          votes


















          47














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


          ];





          share|improve this answer

























          • Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

            – floriankrueger
            Sep 26 '14 at 20:35






          • 2





            Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

            – timanglade
            Sep 28 '14 at 3:24











          • @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

            – cjwirth
            Feb 10 '15 at 1:59











          • @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

            – timanglade
            Feb 11 '15 at 7:15











          • Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

            – cjwirth
            Feb 11 '15 at 10:46


















          11














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






          share|improve this answer


















          • 3





            This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

            – Le Duc Duy
            Jan 24 '15 at 9:09


















          10














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






          share|improve this answer























          • I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

            – floriankrueger
            Nov 4 '16 at 11:23






          • 1





            To the top! This is the correct answer!

            – Alex Bartiş
            Mar 12 '17 at 8:57


















          5














          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"






          share|improve this answer
































            1














            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)

            ];





            share|improve this answer























            • nice idea, I'm definately going to try that :) thank you!

              – floriankrueger
              May 28 '15 at 5:24


















            0














            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.






            share|improve this answer






















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26067193%2fclear-complete-realm-database%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              47














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


              ];





              share|improve this answer

























              • Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

                – floriankrueger
                Sep 26 '14 at 20:35






              • 2





                Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

                – timanglade
                Sep 28 '14 at 3:24











              • @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

                – cjwirth
                Feb 10 '15 at 1:59











              • @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

                – timanglade
                Feb 11 '15 at 7:15











              • Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

                – cjwirth
                Feb 11 '15 at 10:46















              47














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


              ];





              share|improve this answer

























              • Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

                – floriankrueger
                Sep 26 '14 at 20:35






              • 2





                Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

                – timanglade
                Sep 28 '14 at 3:24











              • @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

                – cjwirth
                Feb 10 '15 at 1:59











              • @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

                – timanglade
                Feb 11 '15 at 7:15











              • Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

                – cjwirth
                Feb 11 '15 at 10:46













              47












              47








              47







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


              ];





              share|improve this answer















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


              ];






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 25 '16 at 22:47

























              answered Sep 26 '14 at 19:55









              DonVaughnDonVaughn

              10.2k33948




              10.2k33948












              • Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

                – floriankrueger
                Sep 26 '14 at 20:35






              • 2





                Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

                – timanglade
                Sep 28 '14 at 3:24











              • @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

                – cjwirth
                Feb 10 '15 at 1:59











              • @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

                – timanglade
                Feb 11 '15 at 7:15











              • Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

                – cjwirth
                Feb 11 '15 at 10:46

















              • Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

                – floriankrueger
                Sep 26 '14 at 20:35






              • 2





                Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

                – timanglade
                Sep 28 '14 at 3:24











              • @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

                – cjwirth
                Feb 10 '15 at 1:59











              • @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

                – timanglade
                Feb 11 '15 at 7:15











              • Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

                – cjwirth
                Feb 11 '15 at 10:46
















              Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

              – floriankrueger
              Sep 26 '14 at 20:35





              Yes, I already tried that but the problem is that this approach gets really nasty when there are some threads in the background who try to do something on the realm while the user decides to log out. Deleting the file on disk has the disadvantage that it ignores the transactions which might currently be open and eventually causes the app to crash. And I really don't want to start synchronizing all my database accesses .. Thanks anyways :)

              – floriankrueger
              Sep 26 '14 at 20:35




              2




              2





              Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

              – timanglade
              Sep 28 '14 at 3:24





              Hey Tim from Realm here. DonamiteIsTnt has the right idea but you’re right that there are edge cases to this approach. We will be introducing a method to delete realm files in a safe way very soon. Sorry about this!

              – timanglade
              Sep 28 '14 at 3:24













              @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

              – cjwirth
              Feb 10 '15 at 1:59





              @timanglade Any word on how this method is coming along? I can't seem to find it, but it would be a great feature to be able to just delete and recreate a realm file

              – cjwirth
              Feb 10 '15 at 1:59













              @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

              – timanglade
              Feb 11 '15 at 7:15





              @cjwirth as described below, it’s here: realm.io/docs/cocoa/api/Classes/RLMRealm.html#//api/name/…

              – timanglade
              Feb 11 '15 at 7:15













              Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

              – cjwirth
              Feb 11 '15 at 10:46





              Ah, thanks... I was kind of hoping you meant an api to delete the file. We only use it as a cache, and deleting/recreating the file is easier than dealing with migrations.

              – cjwirth
              Feb 11 '15 at 10:46













              11














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






              share|improve this answer


















              • 3





                This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

                – Le Duc Duy
                Jan 24 '15 at 9:09















              11














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






              share|improve this answer


















              • 3





                This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

                – Le Duc Duy
                Jan 24 '15 at 9:09













              11












              11








              11







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






              share|improve this answer













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







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 5 '14 at 17:07









              jpsimjpsim

              12.2k34062




              12.2k34062







              • 3





                This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

                – Le Duc Duy
                Jan 24 '15 at 9:09












              • 3





                This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

                – Le Duc Duy
                Jan 24 '15 at 9:09







              3




              3





              This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

              – Le Duc Duy
              Jan 24 '15 at 9:09





              This one won't work if there's pending migration. Use @DonamiteIsTnt answer if you want to bypass migration

              – Le Duc Duy
              Jan 24 '15 at 9:09











              10














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






              share|improve this answer























              • I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

                – floriankrueger
                Nov 4 '16 at 11:23






              • 1





                To the top! This is the correct answer!

                – Alex Bartiş
                Mar 12 '17 at 8:57















              10














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






              share|improve this answer























              • I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

                – floriankrueger
                Nov 4 '16 at 11:23






              • 1





                To the top! This is the correct answer!

                – Alex Bartiş
                Mar 12 '17 at 8:57













              10












              10








              10







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






              share|improve this answer













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







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 3 '16 at 17:26









              jonchoijonchoi

              10114




              10114












              • I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

                – floriankrueger
                Nov 4 '16 at 11:23






              • 1





                To the top! This is the correct answer!

                – Alex Bartiş
                Mar 12 '17 at 8:57

















              • I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

                – floriankrueger
                Nov 4 '16 at 11:23






              • 1





                To the top! This is the correct answer!

                – Alex Bartiş
                Mar 12 '17 at 8:57
















              I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

              – floriankrueger
              Nov 4 '16 at 11:23





              I don't know in which version exactly that was introduced but using deleteRealmIfMigrationNeeded is actually the correct way afaik now.

              – floriankrueger
              Nov 4 '16 at 11:23




              1




              1





              To the top! This is the correct answer!

              – Alex Bartiş
              Mar 12 '17 at 8:57





              To the top! This is the correct answer!

              – Alex Bartiş
              Mar 12 '17 at 8:57











              5














              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"






              share|improve this answer





























                5














                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"






                share|improve this answer



























                  5












                  5








                  5







                  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"






                  share|improve this answer















                  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"







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 9 '14 at 20:57

























                  answered Oct 9 '14 at 20:48









                  Glen SelleGlen Selle

                  3,23743056




                  3,23743056





















                      1














                      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)

                      ];





                      share|improve this answer























                      • nice idea, I'm definately going to try that :) thank you!

                        – floriankrueger
                        May 28 '15 at 5:24















                      1














                      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)

                      ];





                      share|improve this answer























                      • nice idea, I'm definately going to try that :) thank you!

                        – floriankrueger
                        May 28 '15 at 5:24













                      1












                      1








                      1







                      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)

                      ];





                      share|improve this answer













                      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)

                      ];






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 27 '15 at 12:26









                      Steve PascoeSteve Pascoe

                      17628




                      17628












                      • nice idea, I'm definately going to try that :) thank you!

                        – floriankrueger
                        May 28 '15 at 5:24

















                      • nice idea, I'm definately going to try that :) thank you!

                        – floriankrueger
                        May 28 '15 at 5:24
















                      nice idea, I'm definately going to try that :) thank you!

                      – floriankrueger
                      May 28 '15 at 5:24





                      nice idea, I'm definately going to try that :) thank you!

                      – floriankrueger
                      May 28 '15 at 5:24











                      0














                      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.






                      share|improve this answer



























                        0














                        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.






                        share|improve this answer

























                          0












                          0








                          0







                          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.






                          share|improve this answer













                          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.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 7 at 12:26









                          Prathma RastogiPrathma Rastogi

                          93




                          93



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26067193%2fclear-complete-realm-database%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                              2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                              Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme