Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CoreDataDemoSnippet
#pragma mark - CoreDataAbout
- (void)saveContext
{
NSError* error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error :%@, %@", error, [error userInfo]);
abort();
}else{
NSLog(@"save success!");
}
}
}
- (NSURL*)applicationDocDir
{
NSURL* url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
NSLog(@"%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]);
return url;
}
// 后缀为.xcdatamodeld的包,里面是.xcdatamodel文件,用数据模型编辑器编辑
// 编译后为.momd或.mom文件
- (NSManagedObjectModel*)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL* modelURL = [[NSBundle mainBundle] URLForResource:@"Journal" withExtension:@"momd"];
NSLog(@"model url: %@", [modelURL path]);
self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return self.managedObjectModel;
}
- (NSManagedObjectContext*)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator* coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
self.managedObjectContext = [[NSManagedObjectContext alloc]init];
[self.managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return self.managedObjectContext;
}
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL* storeUrl = [[self applicationDocDir] URLByAppendingPathComponent:@"Journal.sqlite"];
NSError* error = nil;
self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
NSLog(@"Error: %@, %@", error, [error userInfo]);
}
return self.persistentStoreCoordinator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment