ios coredata的用法和利弊

第一部分coredata的用法

先建立一个使用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学习教程,你很容易被各种各样的术语吓倒。事实上大部分学习教程都首先假定你已经知道了这些术语,而如果你不了解这些术语,那将会陷入困惑中。所以首先要知道关键的术语

  

posted @ 2015-08-02 04:39  张雄杰vip  阅读(287)  评论(0编辑  收藏  举报