1.在创建Project时如果选择上Core Data的话,在AppDelegate中会出现几个方法用于设置Core Data的栈
一个创建管理对象上下文,一个创建管理对象模型,还有一个创建持久性存储协调器
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "cc.linkmob.FailedBankCD" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"FailedBankCD" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"FailedBankCD.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
管理对象模型(Managed Object Model):可以认为是数据库的架构。管理对象模型包含了每个保存在数据库中对象(实体)的定义信息。一般情况下,可以使用Xcode的编辑器来设置数据库中的对象,比如说对象的属性,数据之间的关系。也可以用代码进行设置。
持久性存储协调器(Persistent Store Coordinator):可以认为是数据库的连接。在这里,将要设置数据存储的名称和位置,以及数据存储的时间。
管理对象上下文(Managed Object Context):可以认为是数据库中对象的实际内容。这是三个类中最重要的。在获取,插入或者删除对象时都要调用到管理对象上下文。
2.两个实体中,如果创建了实体A有一个对应关系到实体B,则也应该创建一个实体B到实体A的关系。
3.将Delete Rule设置为Cascade(级联)的话,意味着在Core Data删除一个对象的话,与之相关的对象也会被删除。
4.Fetch Request :可以认为是SQL中的SELECT。
5.因为NSManagedObject不是一个强类型的类,所以在编码过程中比较容易出错,所以最好的方法是位每个Entity创建一个Model:
注意选择的是NSManagedObject subclass
完成以后要注意关系对象的类名,有可能为NSManagedObject,要对其更正
6.在第二篇教程中http://www.raywenderlich.com/12170/core-data-tutorial-how-to-preloadimport-existing-data-updated
由于Xcode的更新,所以在创建新项目中OS X命令行没有了使用Core Data的选项,所以只能手动添加以下方法
static NSManagedObjectModel *managedObjectModel() {
static NSManagedObjectModel *model = nil;
if (model != nil) {
return model;
}
NSString *path = @"FailedBankCD";
NSURL *modelURL = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"momd"]];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return model;
}
static NSManagedObjectContext *managedObjectContext() {
static NSManagedObjectContext *context = nil;
if (context != nil) {
return context;
}
@autoreleasepool {
context = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel()];
[context setPersistentStoreCoordinator:coordinator];
NSString *STORE_TYPE = NSSQLiteStoreType;
NSString *path = [[[NSProcessInfo processInfo] arguments] objectAtIndex:0];
path = [path stringByDeletingPathExtension];
NSURL *url = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"sqlite"]];
NSError *error;
NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE
configuration:nil
URL:url
options:nil
error:&error];
if (newStore == nil) {
NSLog(@"Store Configuration Failure %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
}
}
return context;
}
记得导入CoreData.framework,并在main.m文件中#import <CoreData/CoreData.h>
7.教程三(http://www.raywenderlich.com/999/core-data-tutorial-for-ios-how-to-use-nsfetchedresultscontroller)
1)使用NSFetchedResultsController的时候,需要在提取请求中设置一个排序描述(NSSortDescriptor)。排序描述不仅可以排序所返回的对象的特性,还能排序相关对象的特性。
2)需要在提取请求中将批量大小设置成较小的。
3)在完成匹配后,需要创建一个NSFetchedRequestController