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(@"删除成功"); }
相关文章推荐
- Java多线程(二)、线程的生命周期和状态控制
- HDOJ-3949 XOR(高斯消元)
- [2015.07.27]万峰图片批量处理专家 v8.6
- ios入门之c语言篇——基本函数——2——判断闰年
- JavaScript中指针和地址理解
- .h .m切换
- UVa673 Parentheses Balance
- CF Gym 100637J Superfactorial numeral system (构造)
- CF Gym 100637K Microcircuits (DP)
- CF Gym 100637G \#TheDress (水)
- CF Gym 100637F The Pool for Lucky Ones
- CF Gym 100637B Lunch(拆分子问题)
- ios入门之c语言篇——基本函数——1——随机数生成
- Java练习题(三)
- iOS js交互(OC)
- hihoCoder - 1066 - 无间道之并查集
- CF Gym 100637A Nano alarm-clocks
- go-并发与并行
- 杭电 3788 zoj问题
- springMVC工作流程