I am one of the great unwashed masses of .NET developers keen to try their hands at Mac OS X development. At the moment I am trying to figure out the various elements of Cocoa and getting a bit stuck on Core Data.
I noticed most of the documentation and resources available on the Web involve a broad end-to-end tutorial, beginning from models, generating classes, Document-based UI, etc. Not enough seem to be focused on each bit, or at least not enough examples.
Can someone please point me in the right direction, be it online material or books, that can give me detailed instruction of various bits? Maybe I'm stuck in the .NET world but I still think in terms of data access layer, etc. I'd like to know the basics of "CRUD", in setting up a persistent store, creating an entity, editing, saving to store, etc. Just the basics, without elaborating on the UI. It'd also be nice if I can unit test the various bits.
I guess I am trying to get into the correct mindset here - do any .NET devs out there know of appropriate reading material for people like us looking at Cocoa programming?
Many thanks, Dany.
First, as Apple's documentation (and recurring comments from Apple engineers) state, Core Data is an "advanced" Cocoa technology. Grokking Core Data requires knowledge of a lot of Cocoa paradigms and patterns. Seriously, learn Cocoa first. Then write a project (or several) without Core Data. Then learn Core Data. Seriously.
To quiet your curiosity, I'll take a stab at the CRUD answer, though it's not going to be the answer you want. The answer is that there is no CRUD pattern for Core Data, at least not the way you think of it. The reason is that Core Data is not a data access layer. It is an object graph management framework. That means the explicit, intended job of Core Data is to manage a graph of object instances. This graph has constraints (such as cardinality of relationships or constraints on individual instance attributes) and rules for cascading changes (such as a delete) through the graph. Core Data manages these constraints. Because an object graph may be too large to be stored in memory, Core Data provides an interface to your object graph that simulates[1] an entire object graph in memory via faulting (object instances are not "faults" when first brought into a managed object context and are "fired" to populate their attributes from the persistent store lazily) and uniquing (only one in-memory instance of a particular entity instance (in the persistent store) is created in the context).
Core Data just happens to use an on-disk persistent store to implement the interface of a large object graph. In the case of an SQLite persistent store, this implementation just happens to use a SQL-compatible database. This is an implementation detail, however. You can, for example create an in-memory persistent store that does not persist anything to disk but allows Core Data to manage your object graph as usual. Thus, Core Data is not really a data access layer. To think of it in these terms will miss it's true power and will lead to frustration. You can't use Core Data with an arbitrary data base schema (this is why all Core Data tutorials start with creating the NSManagedObjectModel). You shouldn't use Core Data as a persistence framework and use a separate model layer; you should use Core Data as a model layer and take advantage of Core Data's ability to persist the model's object graph to disk for you.
That said, to create an NSManagedObjectContext
(which provides the object graph interface I described above):
NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]]; // though you can create a model on the fly (i.e. in code)
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSError *err;
// add an in-memory store. At least one persistent store is required
if([psc addPersistentStoreWithType:NSInMemoryPersistentStore configuration:nil URL:nil options:nil error:&err] == nil) {
NSLog(@"%@",err);
}
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:psc];
(note that I'm assuming you're using Garbage Collection; this code leaks in a manual memory management environment).
To add an entity instance (continuting with moc
from above):
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:moc];
//entity will be nil if MyEntity doesn't exist in moc.persistentStoreCoordinator.managedObjectModel
NSManagedObject *obj = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:moc];
Notice that you need an entity description to create a managed object (why tutorials start with the model) and that you can't create a managed object without a managed object context.
To update an entity instance:
[obj setValue:myValue forKey:@"attributeKey"]; //or use any method on `obj` that updates its state
NSError *err;
if(![moc save:&err]) {
NSLog(@"%@", err); // an erro occurred in saving, perhaps due to optimistic locking failure
}
To delete an entity instance:
[moc deleteObject:obj];
if(![moc save:&err]) {
NSLog(@"%@", err); // an erro occurred in saving, perhaps due to optimistic locking failure
}
[1]: For binary or XML persistent stores, the entire graph is stored in memory
I would take the following route:
Further reading:
As always: the book Cocoa Programming for Mac OS X
Document-Based Application Architecture (ADC)
And finally: A comparison between some aspects of Cocoa and .net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With