Home > CodeSnippets, iOS, Xcode > Core Data

Core Data

– Add Core Data Framework and the SQlite library “libsqlite3.dylib” to your project.
– Add #import <Cocoa/Cocoa.h> to your prefix header.
– Create managed object model
– Use NSManagedObject as parent class of your entity classes or generate class out of the object model file/new file/…
– Add following to your App Delegate to set up the Managed Objects and the Managed Object Context:


...
@interface AppDelegate : NSObject <UIApplicationDelegate> {
...
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
...
}
@property (nonatomic, retain, readonly) NSManagedObjectModel
   *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext
   *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator
   *persistentStoreCoordinator;
...

@implementation AppDelegate
...
managedObjectModel = [[NSManagedObjectModel alloc] init];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
   initWithManagedObjectModel:managedObjectModel];
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:
   persistentStoreCoordinator];
...

By convention, you can often get a context from a view controller. It’s up to you, though, to follow this pattern.
When you implement a view controller that integrates with Core Data, you can add an NSManagedObjectContext property.
A view controller typically shouldn’t retrieve the context from a global object such as the application delegate. This tends to make the application architecture rigid. Neither should a view controller typically create a context for its own use. This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.
When you create a view controller, you pass it a context. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed.

Create and save a Managed Object:


ManagedObject* managedObject = (ManagedObject*) [NSEntityDescription
   insertNewObjectForEntityForName:@"ManagedObject"
   inManagedObjectContext:managedObjectContext];
NSError* error;
if(![managedObjectContext save:&error]) {
   // Error handling
   NSLog(@"Unresolved Core Data Save error %@, %@",
     error, [error userInfo]);
}

Create the Request:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
  inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

Set the Sort Descriptor:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
  initWithKey:@"creationDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];

Set the predicate:


(NSPredicate *) predicate = [NSPredicate
   predicateWithFormat:@"(Name == %@)", @"Fred"];
 [request setPredicate:predicate];

Execute the Request:

NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext
   executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error.
}

Finish Up:

[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];

Update managed data object with key-value-coding:

[managedObject setValue:@"Tea Time with Moby" forKey:@"title"];
NSError* error;
if(![managedObjectContext save:&error]) {
   // Error handling
}

Getting a value with key-value-coding:

[managedObject valueForKey:@"title"];

Deleting Managed Object:

[managedObjectContext deleteObject:managedObject];
NSError* error;
if(![managedObjectContext save:&error]) {
   // Error handling
}

Request example:

+(NSMutableArray *) searchObjectsInContext: (NSString*)
   entityName : (NSPredicate *) predicate : (NSString*) sortKey : (BOOL)
  sortAscending : (NSManagedObjectContext *) managedObjectContext
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
   inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

// If a predicate was passed, pass it to the query
if(predicate != nil)
{
[request setPredicate:predicate];
}

// If a sort key was passed, use it for sorting.
if(sortKey != nil)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
   initWithKey:sortKey ascending:sortAscending];
NSArray *sortDescriptors = [[NSArray alloc]
   initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
}

NSError *error;

NSMutableArray *mutableFetchResults = [[[managedObjectContext
   executeFetchRequest:request error:&error] mutableCopy] autorelease];

[request release];

return mutableFetchResults;
}

+(NSMutableArray *) getObjectsFromContext: (NSString*) entityName : (NSString*)
   sortKey : (BOOL) sortAscending : (NSManagedObjectContext *)
   managedObjectContext
{
return [self searchObjectsInContext:entityName :nil :sortKey
   :sortAscending :managedObjectContext];
}
Categories: CodeSnippets, iOS, Xcode
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: