Overview Structure with Core Data in iOS
In this article, I’ll present the entry level structure of Core Data used in iOS development. For detail programming guide on this topic, please follow this link. This article is mainly for my deep study reference only.
This image is “borrowed” from objc.io for education purpose. If any violation comes with it, the image will be removed.
This image perfectly explained the structure of Core Data in iOS.
NSManagedObjectContext is the handler we use to present model(NSMangedObject) to the out world, which includes data detail and relationship between data.
NSPersistentStoreCoordinator is like a traffic commander shows where the data could be CRUD for NSMangedObjectContext.
NSPersistentStore is the place knows how to store data, it will use SQLite and save the data on File System.
For most of the cases, single NSManagedObjectContext with single NSPersistentStore are widely used here.
So, what we actually use with View and Controller is NSManagedObjectContext. Let’s see how we create it.
1, Create NSManagedObjectContext.
self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
2, Add NSPersistentStoreCoordinator to NSManagedObjectContext.
self.managedObjectContext.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[[NSManagedObjectModel alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"NestedTodoList" withExtension:@"momd"]]];
3, Add NSPersistentStore to NSPersistentStoreCoordinator.
NSError* error; [self.managedObjectContext.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[[[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL] URLByAppendingPathComponent:@"db.sqlite"] options:nil error:&error]; if (error) { NSLog(@"error: %@", error); }
Then, your NSMangedObjectContext(self.managedObjectContext) is ready to use if no error ocurred.










