ios coredata的用法
2015-04-23 11:13
393 查看
第一部分coredata的用法
先建立一个使用use coredata的工程
![](http://img.blog.csdn.net/20150423111458140?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXV6aGVuaHVh/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
在。xcdatamodeld文件中建立表格并为表格添加属性
![](http://img.blog.csdn.net/20150423111534020?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXV6aGVuaHVh/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
为表格添加关系,
![](http://img.blog.csdn.net/20150423111447573?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXV6aGVuaHVh/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
下一步生成表格model
![](http://img.blog.csdn.net/20150423111510193?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXV6aGVuaHVh/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](http://img.blog.csdn.net/20150423111521206?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXV6aGVuaHVh/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
其中生成的model:User和Department里面的属性用的是@dynamic
@property有两个对应的词,一个是@synthesize,一个是@dynamic。如果@synthesize和@dynamic都没写,那么默认的就是@syntheszie var = _var;
@synthesize的语义是如果你没有手动实现setter方法和getter方法,那么编译器会自动为你加上这两个方法。
@dynamic告诉编译器,属性的setter与getter方法由用户自己实现,不自动生成。(当然对于readonly的属性只需提供getter即可)。假如一个属性被声明为@dynamic var,然后你没有提供@setter方法和@getter方法,编译的时候没问题,但是当程序运行到instance.var =someVar,由于缺setter方法会导致程序崩溃;或者当运行到 someVar = var时,由于缺getter方法同样会导致崩溃。编译时没问题,运行时才执行相应的方法,这就是所谓的动态绑定。
然后会再appdelegate里自动生成以下代码:
这些代码知道具体作用就好,如果想自己手动建立起来coredata文件,也可以自己手动写
下面就是在viewcontroller的具体操作,
先引入appdelegate和User,Department的头文件
在viewcontroller里添加
@property (strong, nonatomic)AppDelegate *myAppDelegate;属性
然后,
具体操作,
添加:
coredata并非严格的说是对sqlite数据库的一个封装,也可以用其他的数据库,并不一定要使用sqlite3,当然了coredata的好处还是非常多的,高效,简介,能节省至少50%的代码量,条目清新
对于iOS开发者来说,会使用Core Data是一项必备技能。 没有它,很多app都不会存在。当在互联网上四处搜索Core Data学习教程,你很容易被各种各样的术语吓倒。事实上大部分学习教程都首先假定你已经知道了这些术语,而如果你不了解这些术语,那将会陷入困惑中。所以首先要知道关键的术语
先建立一个使用use coredata的工程
在。xcdatamodeld文件中建立表格并为表格添加属性
为表格添加关系,
下一步生成表格model
其中生成的model:User和Department里面的属性用的是@dynamic
@property有两个对应的词,一个是@synthesize,一个是@dynamic。如果@synthesize和@dynamic都没写,那么默认的就是@syntheszie var = _var;
@synthesize的语义是如果你没有手动实现setter方法和getter方法,那么编译器会自动为你加上这两个方法。
@dynamic告诉编译器,属性的setter与getter方法由用户自己实现,不自动生成。(当然对于readonly的属性只需提供getter即可)。假如一个属性被声明为@dynamic var,然后你没有提供@setter方法和@getter方法,编译的时候没问题,但是当程序运行到instance.var =someVar,由于缺setter方法会导致程序崩溃;或者当运行到 someVar = var时,由于缺getter方法同样会导致崩溃。编译时没问题,运行时才执行相应的方法,这就是所谓的动态绑定。
然后会再appdelegate里自动生成以下代码:
#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 eims.CoreDatatest 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:@CoreDatatest 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:@CoreDatatest.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(); } } }
这些代码知道具体作用就好,如果想自己手动建立起来coredata文件,也可以自己手动写
下面就是在viewcontroller的具体操作,
先引入appdelegate和User,Department的头文件
在viewcontroller里添加
@property (strong, nonatomic)AppDelegate *myAppDelegate;属性
然后,
具体操作,
添加:
User*user = (User*)[NSEntityDescription insertNewObjectForEntityForName:@User inManagedObjectContext:self.myAppDelegate.managedObjectContext]; [user setName:_nametextfield.text]; [user setAge:[NSNumber numberWithInteger:[_agetextfield.text integerValue]]]; [user setSex:_sextextfield.text]; NSError*error; BOOL isSaveSuccess = [myAppDelegate.managedObjectContext save:&error];//保存(容易忘) if (!isSaveSuccess) { NSLog(@Error:%@,error); _attentiontextview.text = [NSString stringWithFormat:@Error:%@,error]; }else{ NSLog(@Save Successful!); _attentiontextview.text = @Save Successful!; } 查询: //数据请求(请求):命令集 NSFetchRequest*request = [[NSFetchRequest alloc]init]; //NSEntityDescription(实体描述):表 NSEntityDescription*user = [NSEntityDescription entityForName:@Department inManagedObjectContext:myAppDelegate.managedObjectContext]; [request setEntity:user]; NSError*error; NSArray*mutablefetchResult = [myAppDelegate.managedObjectContext executeFetchRequest:request error:&error]; if (mutablefetchResult == nil) { NSLog(@Error: %@,mutablefetchResult); } NSLog(@the count of entry:%lu,[mutablefetchResult count]); NSString*str = @; for (Department*user in mutablefetchResult) { // NSLog(@name:%@------age:%@-------sex:%@,user.name,user.age,user.sex); // str = [str stringByAppendingFormat:@name:%@------age:%@-------sex:%@ ---depart:%@ ,user.name,user.age,user.sex,user.userrelationship.departmentname]; str = [str stringByAppendingFormat:@name:%@------ ,user.departmentname]; } NSLog(@str:%@,str); 更新: //NSFetchRequest 数据请求(请求):命令集 NSFetchRequest*request = [[NSFetchRequest alloc]init]; //NSEntityDescription(实体描述):表 NSEntityDescription*user = [NSEntityDescription entityForName:@User inManagedObjectContext:myAppDelegate.managedObjectContext]; [request setEntity:user]; //设置查询条件 NSPredicate (谓词):查询语句 NSPredicate*predicate = [NSPredicate predicateWithFormat:@name == %@,@lisi]; [request setPredicate:predicate]; NSError*error; NSArray * mutablFetchResult = [myAppDelegate.managedObjectContext executeFetchRequest:request error:&error]; if (mutablFetchResult == nil) { NSLog(@Error:%@,error); _attentiontextview.text = [NSString stringWithFormat:@Error:%@,error]; } NSLog(@the count of entry:%lu,[mutablFetchResult count]); for (User*user in mutablFetchResult) { [user setAge:[NSNumber numberWithInteger:999]]; } //判断是否修改成功 BOOL isSaveSuccess = [myAppDelegate.managedObjectContext save:&error];//保存(容易忘) if (!isSaveSuccess) { NSLog(@Error:%@,error); _attentiontextview.text = [NSString stringWithFormat:@Error:%@,error]; }else{ NSLog(@update Successful!); _attentiontextview.text = @update Successful!; } 删除: //数据请求(命令集) NSFetchRequest*request = [[NSFetchRequest alloc]init]; //实体描述(表) NSEntityDescription*user = [NSEntityDescription entityForName:@Department inManagedObjectContext:myAppDelegate.managedObjectContext]; [request setEntity:user]; //设置查询条件 NSPredicate* predicate = [NSPredicate predicateWithFormat:@departmentname == %@,@公共事业部]; [request setPredicate:predicate]; NSError*error; NSArray*mutableFetchResult = [myAppDelegate.managedObjectContext executeFetchRequest:request error:&error]; if (mutableFetchResult == nil) { NSLog(@Error:%@,error); _attentiontextview.text = [NSString stringWithFormat:@Error:%@,error]; } NSLog(@mutableFetchResult %lu,[mutableFetchResult count]); for (User*user in mutableFetchResult) { [myAppDelegate.managedObjectContext deleteObject:user]; } //判断是否删除成功 BOOL isDeleteSuccess = [myAppDelegate.managedObjectContext save:&error];//保存(容易忘) if (!isDeleteSuccess) { NSLog(@Error:%@,error); _attentiontextview.text = [NSString stringWithFormat:@Error:%@,error]; }else{ NSLog(@delete Successful!); _attentiontextview.text = @delete Successful!; }
coredata并非严格的说是对sqlite数据库的一个封装,也可以用其他的数据库,并不一定要使用sqlite3,当然了coredata的好处还是非常多的,高效,简介,能节省至少50%的代码量,条目清新
对于iOS开发者来说,会使用Core Data是一项必备技能。 没有它,很多app都不会存在。当在互联网上四处搜索Core Data学习教程,你很容易被各种各样的术语吓倒。事实上大部分学习教程都首先假定你已经知道了这些术语,而如果你不了解这些术语,那将会陷入困惑中。所以首先要知道关键的术语
相关文章推荐
- ios coredata的用法和利弊
- ios coredata的用法和利弊
- iOS中coreData的用法
- iOS的CoreData用法
- iOS中coreData的用法
- iOS CoreData的基本用法
- iOS 数据持久化的NSKeyedArchiver CoreData FMDB几种方式的用法
- ios coredata的用法和利弊
- iOS的CoreData用法
- iOS Core Data 用法
- iOS~CoreData入门
- ios中coredata的使用
- IOS CoreText.framework --- 基本用法
- Core Data Tutorial for iOS: Getting Started
- iOS-Core Data创建对象文件报错解决办法
- iOS学习之CoreData的增删改查
- iOS CoreData 的相关使用方法。
- (转载)Core Data Tutorial for iOS: Getting Started
- iOS 认识CoreData-多线程
- CoreData和ios开发中的数据库,直接查询模拟器内的sqlite数据