您的位置:首页 > 其它

CoreData入门例子

2015-07-25 16:43 239 查看

创建一个CoreData工程



然后我们在AppDelegate可以看到Xcode为我们生成:

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
// The direc tory the application uses to store the Core Data store file. This code uses a directory named "com.xiaozhi.CoreDataDemo" 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:@"CoreDataDemo" 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:@"CoreDataDemo.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();
}
}
}


基本配置工作,Xcode已经帮我们做好了。我们了解下面几个类型基本概念

NSManagedObjectModel :这个就是我们的实例Model

NSPersistentStoreCoordinator:用来连接数据库的中间件

NSManagedObjectContext :它与我们打交道相对会多一点

添加实体与属性

话不多说,按照下图那样,把Entity(实体)和属性添加完毕。



增删改查操作

添加

NSManagedObjectContext *context = [[self appDelegate] managedObjectContext];
NSManagedObjectModel * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
[student setValue:@12 forKey:@"age"];
[student setValue:@123231 forKey:@"id"];
[student setValue:@"XiDaDa" forKey:@"name"];
NSError *error;
if (![context save:&error]) {
NSLog(@"保存失败");
}


查询

NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray * students = [context executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *object in students) {
NSLog(@"%@ > %@ > %@",[object valueForKey:@"age"],[object valueForKey:@"id"],[object valueForKey:@"name"]);
}


更新

NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
request.predicate = [NSPredicate predicateWithFormat:@"name = %@",@"XiDaDa"];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
request.entity = entity;
NSArray* students = [context executeFetchRequest:request error:nil];
for (NSManagedObject *object in students) {
NSLog(@"查询出来的:[name:%@]",[object valueForKey:@"name"]);
[object setValue:@"DaMeng" forKey:@"name"];
}

NSError *error;
if (![context save:&error]) {
NSLog(@"%@",error.userInfo);
}else{
NSLog(@"更新成功");
}


删除

NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
request.predicate = [NSPredicate predicateWithFormat:@"name = %@",@"XiDaDa"];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
request.entity = entity;
NSArray* students = [context executeFetchRequest:request error:nil];
for (NSManagedObject *object in students) {
NSLog(@"查询出来的:[name:%@]",[object valueForKey:@"name"]);
[context deleteObject:object];
}

NSError *error;
if (![context save:&error]) {
NSLog(@"%@",error.userInfo);
}else{
NSLog(@"删除成功");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: