iOS Tutorial Save Data in Core Data

On November 20, 2014, in iPhone iPad Object-C, by James Liu
apple

In last tutorial, we successfully create a new iOS project with Core Data Framework. We also design a Managed Object Model in the Xcode data model design tool and automatically generate the classes associated with the entities in the model. So, in this post, we will continue doing the app and I will show you how to initialise the managed object model in the app and how to save save data by core data.

Initialise Managed Object Model in iOS

There are three steps to init Managed Object Model in iOS. First of all, we need to create a NSManagedObjectModel object (What’s Managed Object Model). Here are the example source code to show you how to achieve this:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataTest" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

Then, we will create a NSPersistentStoreCoordinator object. It will work as persistent stores which will handle with all physical saving jobs or writing data on the device basing on the Managed Object Model. Therefore, to create a NSPersistentStoreCoordinator object, we need to specify the NSManagedObjectModel object and the location where we want to save the data. Here is the source code:

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
NSError *error = nil;
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]

In the last step, we will create a NSManagedObjectContext instance, which will associate with NSPersistentStoreCoordinator instance which we created in second step. NSManagedObjectContext is the instance which we will use to fetch data and save data in the future.

_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:_persistentStoreCoordinator];

Save Data In iOS Core Data Framework

Right now, we have the NSManagedObjectContext to save data and load data in core data. In this example app, I will preload some data when we run the app at the first time. I will save four people’s information in the core data. Here is the example source code for saving data in core data.

    UserProfile *up = [NSEntityDescription insertNewObjectForEntityForName:@"UserProfile" inManagedObjectContext:self.managedObjectContext];
up.id = [NSNumber numberWithInt:1];
    up.username = @"James Bond";
    up.password = @"123456";
    up.createDate = [NSDate date];
    up.gender = [NSNumber numberWithInt:1];
    up.address = @"1 New Orchard Road Armonk";
    up.email = @"james@gmail.com";
    
    up = [NSEntityDescription insertNewObjectForEntityForName:@"UserProfile" inManagedObjectContext:self.managedObjectContext];
    up.id = [NSNumber numberWithInt:2];
    up.username = @"Tommy Pett";
    up.password = @"123456";
    up.createDate = [NSDate date];
    up.gender = [NSNumber numberWithInt:1];
    up.address = @"1600 Amphitheatre Parkway";
    up.email = @"tommy.pett@hotmail.com";
    
    up = [NSEntityDescription insertNewObjectForEntityForName:@"UserProfile" inManagedObjectContext:self.managedObjectContext];
    up.id = [NSNumber numberWithInt:2];
    up.username = @"Andrew Wang";
    up.password = @"123456";
    up.createDate = [NSDate date];
    up.gender = [NSNumber numberWithInt:1];
    up.address = @"1 Infinite Loop in Cupertino";
    up.email = @"andrew@yahoo.com";
    
    up = [NSEntityDescription insertNewObjectForEntityForName:@"UserProfile" inManagedObjectContext:self.managedObjectContext];
    up.id = [NSNumber numberWithInt:2];
    up.username = @"Angie Lawrence";
    up.password = @"123456";
    up.createDate = [NSDate date];
    up.gender = [NSNumber numberWithInt:1];
    up.address = @"Business Center 1030 E.";
    up.email = @"angie.l@outlook.com";
    
    NSError *error = nil;
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

UserProfile is the entity class which we generated from Managed Object Model (How to generate entity class automatically?) The above example inserts four UserProfile entities into core data, then saves the changes. Core data is a simple way to save local data in iOS apps.

Init App Data At First Launch

In case there are some people don’t know how to init app data at the first time when the app is launched, I give more example source code here. I believe there may be more efficient way to do this. You can level comment below if you have a better way.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *isFirstLaunch = [defaults objectForKey:@"isFirstLaunch"];
    if(!isFirstLaunch)
    {
        [defaults setObject:@"YES" forKey:@"isFirstLaunch"];
        //doing your init tasks here
        [defaults synchronize];
    }
    
    return YES;
}

In this tutorial, we covered how to init managed object model and how to save data in core data at the first time when the app is launched. In next post, I will talk about how to load data from core data and how to search data from core data.

 

Leave a Reply

Premium WordPress Themes

WordPress Blog