user1170896
user1170896

Reputation: 739

What's the correct approach to setup CoreData app with iOS 5 and RestKit

Hi all I've built a couple of apps with iOS5 and now I'm about to dive in CoreData. What's the correct approach? Lot's of guides refer to an old XCode version where in project creation wizard the developer could choose "Use CoreData". That way you would get automagically a reference to NSManagedObjectContext. It appears this option no longer exists. So what now? I've read about UIManagedDocument but I don't get how it relates to: the persistentStoreCoordinator, the managedObjectModel, the managedObjectContext. Also I need to make all this work with RestKit which adds even more confusion about what's the correct approach. I need someone to explain or point me in the right direction. Thanks

Upvotes: 1

Views: 652

Answers (2)

netsplit
netsplit

Reputation: 140

Just started using RestKit / Core Data 1 month ago. I read a lot tutorials to get more or less comfortable with the stuff. One of the best tutorial I read was: http://mobile.tutsplus.com/tutorials/iphone/advanced-restkit-development_iphone-sdk/

The "Use Core Data" option when creating a new project e.g. in the Master-Detail-View project template doesn't make sense when using RestKit. The NSPersistentStoreCoordinator for example is managed by RKManagedObjectStore. The NSManagedObjectContext gets automatically created in background. See attached example code to get an idea how it works.

A simple RestKit setup looks like this:

objectManager = [RKObjectManager managerWithBaseURLString:@"http://x.y.z.a"];

NSString *databaseName = @"XYZ.sqlite";
managedObjectStore = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName];
objectManager.objectStore = managedObjectStore;

RKManagedObjectMapping *customerMapping = [RKManagedObjectMapping mappingForClass:[Customer class] inManagedObjectStore:objectManager.objectStore];
[customerMapping mapKeyPathsToAttributes:@"Id", @"customerid", nil];
[customerMapping mapKeyPathsToAttributes:@"Name", @"name", nil];
[customerMapping mapKeyPathsToAttributes:@"Firstname", @"firstname", nil];
customerMapping.primaryKeyAttribute = @"customerid";

//[other mappings incl. relationships]

[objectManager.mappingProvider setObjectMapping:reservationMapping forResourcePathPattern:@"/api/xyz"];

Access to the stored data in Core Data is possible through a NSFetechedResultsController:

NSFetchedResultsController *fetchedResultsController;
fetchedResultsController = [Customer fetchAllSortedBy:@"firstname" ascending:YES withPredicate:nil groupBy:@"firstname"];
fetchedResultsController.delegate = self;

Upvotes: 1

adonoho
adonoho

Reputation: 4339

user1170896,

Use the master-detail project in Xcode 4.5 and you can choose the Core Data option and get all of its boilerplate code.

Andrew

Upvotes: 1

Related Questions