CoreData相比较于SQLite,更具有面向对象的思想,使用更加方便,Apple官方也更推荐使用CoreData。
CoreData在使用的时候可以创建时勾选CoreData,系统会自动创建一个xcdatamodelid类型的数据库,其中可以进行数据的配置。Entity相当于一个表。通过创建NSManagerObject Subclass类型的文件来创建model。创建的model会附带一个+CoreDataProperties的类目,类目中声明了表中的所有属性。
#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 "jinquanbin.CoreData3_12" 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:@"CoreData3_12" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
//持久存储协调器,是context和数据库衔接的桥梁。即数据库和应用数据之间的交互(CRUD)
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns 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:@"CoreData3_12.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;
}
//创建(获取context)
- (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] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_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();
}
}
}
数据库路径(DocumentsDirectory)-> ManagerObjectModel -> NSPersistentStoreCoordinate -> NSManagerObjectContext。CoreData的使用过程中主要对Context进行操作,不必继续写SQLite语句。当然SQLite语句更加灵活,相对而言,CoreData的操作比较固定。
增:
User *user = [NSEntityDescription insertNewObjectForEntity:@"User" inManagerObjectContext:self.managerObjecContext];
user.name = @"Tom";
user.age = @20 //这里不能用int,float这种基本数据类型。
[self.managerObjectContext save:NULL] //就能存储数据到物理数据库。
删:
NSPredicate *predicate = [NSPridicate pridicateWithFormat:@"name = 'Tom'"];
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName@"User"];
fetch.predicate = preidcate];
NSError *error = nil;
NSArray *result = [self managerObjectContext] excuteFetchRequest:fetch error:&error];
for (User *user in result) {
[self.managerObjectContext deleteObject:user]
}
改:
对于修改操作,需要先查询到需要修改的object,然后对其修改,最后保存。
NSPredicate *predicate = [NSPridicate pridicateWithFormat:@"name = 'Tom'"];
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName@"User"];
fetch.predicate = preidcate];
NSError *error = nil;
NSArray *result = [self managerObjectContext] excuteFetchRequest:fetch error:&error];
for (User *user in result)
{
user.name = @"Jack"
[self.managerObjectContext save:NULL]
查:
//NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagerObejctContext:self.managerObjectContext];
//这里还可以使用谓词进行条件查询
NSPredicate *predicate = [NSPridicate pridicateWithFormat:@"name = 'Tom'"];
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName@"User"];
fetch.predicate = preidcate];
NSError *error = nil;
NSArray *result = [self managerObjectContext] excuteFetchRequest:fetch error:&error];