Categories

Reset Core data database inside application

Standard

In iOS app development you might get into a point where you need to reset your full database; which in this case is in core data, quite commonly used in iOS application development. Now the question comes in mind, how do you achieve it? First of all I am assuming, you are not a newbie with iOS and Core Data. Next thing, I am also assuming, you are well aware of core data entity and data persistency.

Now, if you want to remove all your data form the core data object model first thing that pops into your mind might be, query down each and every entity and then delete the data within! Whoa, wait a second dear!!! There is a much easier way, with less hassle (almost none)!

Well, as you’re familiar with core data object model you should probably know, core data has an “sqlite” file working under the hood. To reset the application, you just need to remove the file and recreate it, as simple as that! Amazing, isn’t it?

Okay lets go down to the business right now. Go to the view controller file where you want all the reset thing to take place. Place an action method named resetAllData connected with some user interaction, say button press. The code might look like this:

As you can see, we’re just calling the AppDelegate’s managedObjectContext to recreate it (as simple as that, isn’t it?).

Now, lets move on a little further. When we mean we want to reset all application data, it means every data, including the userDefaults, right? We do use NSUserDefaults a lot to store tiny but useful data, like if the application should run in a silent mode or not etc. Now to clear the userDefaults, just add the following code in the resetAllData method: