
Introduction
Core Data is one of the main storage methods used in iOS development. Normally, storage methods like Core Data and SQLite both have advantages and disadvantages depending on the amount and type of data you need to store and manage. Core Data is more advantageous for iOS.
Core Data is a model layer of your application in the broadest sense possible. It’s the Model in the Model-View-Controller pattern that permeates the iOS SDK.
This blog and the accompanying sample application provide an overview of Core Data.
Use Case
This use case demonstrates the steps for creating an iOS application with Core Data model using iOS Xcode.
What we need to do ?
- Prerequisites
- Open Xcode
- Create a new project
- Store and retrieve the information from Core Data
Create a New Project
Prerequisites
- Download and Install OS X Yosemite version 10.10.1:
https://www.apple.com/in/osx/ - Download and Install Xcode 6:
https://developer.apple.com/xcode/downloads/
Solution
The necessary steps to create a new project are listed below:
Step 1: Open Xcode. Navigate to File > New > Project. Choose Single View Application. Click on Next.
Step 2: The following window opens. Enter in the appropriate values for the fields and select Objective-C as the Language. Check Use Core Data option for iPhone. Click on Next.
Step 3: Create an Objective C class file “ViewController.h” with a subclass “Editor.h”.
We can store and retrieve information by using iOS Core Data technologies. For example, few sample employee details can be stored in iOS_CoreData.xcdatamodeld.
NOTE : Make sure “.xcdatamodeld” file is added into your project explorer.
STEP 4 : Open “AppDelegate.h” and “AppDelegate.m” file. Check if the lines of code listed below are added or not. These lines of code are generated automatically into Xcode when Use Core Data option is checked in the Project Creation window.
#import <UIKit/UIKit.h> #import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext; - (NSURL *)applicationDocumentsDirectory; @end
@synthesize managedObjectContext = _managedObjectContext; @synthesize managedObjectModel = _managedObjectModel; @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; - (NSURL *)applicationDocumentsDirectory - (NSManagedObjectModel *)managedObjectModel - (NSPersistentStoreCoordinator *)persistentStoreCoordinator - (NSManagedObjectContext *)managedObjectContext - (void)saveContext
Step 5 : For UI Design Process, you can either use Storyboard or Xib design pattern. Here, I have created a storyboard option with some i/o fields. The image below shows the View Controller on the left and the Editor on the right.
Step 6 : The code shown below is automatically generated when the connections are made between the Storyboard and the Class files.
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITextFieldDelegate> { UITextField *findTextfield; UIButton *findButton; UILabel *nameTextLabel; UILabel *designationLabel; UILabel *emailLabel; UILabel *phoneLabel; UILabel *cityLabel; UIButton *storeButton; } @property (strong, nonatomic) IBOutlet UITextField *findTextfield; @property (strong, nonatomic) IBOutlet UIButton *findButton; @property (strong, nonatomic) IBOutlet UILabel *nameTextLabel; @property (strong, nonatomic) IBOutlet UILabel *designationLabel; @property (strong, nonatomic) IBOutlet UILabel *emailLabel; @property (strong, nonatomic) IBOutlet UILabel *phoneLabel; @property (strong, nonatomic) IBOutlet UILabel *cityLabel; @property (strong, nonatomic) IBOutlet UIButton *storeButton; - (IBAction)Clickfinder:(id)sender; @end
#import <UIKit/UIKit.h> @interface Editor : UIViewController <UITextFieldDelegate> { UITextField *nameTextfield; UITextField *designationTextfield; UITextField *emailTextfield; UITextField *phoneTextfield; UITextField *cityTextfield; UIButton *submitButton; } @property (strong, nonatomic) IBOutlet UITextField *nameTextfield; @property (strong, nonatomic) IBOutlet UITextField *designationTextfield; @property (strong, nonatomic) IBOutlet UITextField *emailTextfield; @property (strong, nonatomic) IBOutlet UITextField *phoneTextfield; @property (strong, nonatomic) IBOutlet UITextField *cityTextfield; @property (strong, nonatomic) IBOutlet UIButton *submitButton; - (IBAction)Clicksubmit:(id)sender; @end
Step 7 : This step is very important. You should create the Core Data structure for the data model. Open “iOS_CoreData.Xcdatamodeld” file. Click on Add Entity button found on the left corner. Now you can see Entities on the top left side. Double click to rename this to ContactDetails. Then, add attributes with types. For example, I have created five i/o fields in my application ‑ name, designation, email, phone, city with the Type ‘String’.
Step 8 : Open Editor.m file and type in the lines of code given here below. Using these lines of code, you can store the data into CoreDataModel.
- (IBAction)Clicksubmit:(id)sender { AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *newContact; newContact = [NSEntityDescription insertNewObjectForEntityForName:@"ContactDetails" inManagedObjectContext:context]; [newContact setValue: nameTextfield.text forKey:@"name"]; [newContact setValue: designationTextfield.text forKey:@"designation"]; [newContact setValue: emailTextfield.text forKey:@"email"]; [newContact setValue: phoneTextfield.text forKey:@"phone"]; [newContact setValue: cityTextfield.text forKey:@"city"]; nameTextfield.text = @""; designationTextfield.text = @""; emailTextfield.text = @""; phoneTextfield.text = @""; cityTextfield.text = @""; NSError *error; [context save:&error]; NSLog(@"Contact saved"); }
The managed object context (NSManagedObjectContext) is a working area for managed objects. To create a new object, delete an object, or query existing objects, this app interacts with the managed object context. In addition, the managed object context can manage related changes.
An NSEntityDescription object describes an entity in Core Data. Entities are to managed objects what Class is to id. Or, to use a database analogy ‑ what tables are to rows.
Step 9 : Open “ViewController.m” file and type in the lines of code given here below. You can retrieve the data from CoreDataModel by using these lines of code.
- (IBAction)Clickfinder:(id)sender { AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"ContactDetails" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDesc]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", findTextfield.text]; [request setPredicate:pred]; NSManagedObject *matches = nil; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if ([objects count] == 0) { NSLog(@"No matches"); } else { matches = objects[0]; nameTextLabel.text = [matches valueForKey:@"name"]; designationLabel.text = [matches valueForKey:@"designation"]; emailLabel.text = [matches valueForKey:@"email"]; phoneLabel.text = [matches valueForKey:@"phone"]; cityLabel.text = [matches valueForKey:@"city"]; NSLog(@"Matches founded"); } }
Step 10 : Run your project. You can see this simple iOS app with the CoreDataModel application process.
Conclusion
In this blog, we have discussed iOS with Core Data model development using the latest Xcode (6.x). Here, we have demonstrated how to create offline data storage. Using this blog as a base, many more data storage processes can be developed in future.
References
http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started