首页 > 代码库 > ios coredata的用法和利弊

ios coredata的用法和利弊

第一部分coredata的用法

先建立一个使用use coredata的工程,

技术分享

在。xcdatamodeld文件中建立表格并为表格添加属性

技术分享


为表格添加关系,技术分享

下一步生成表格model

技术分享

技术分享

其中生成的model:User和Department里面的属性用的是@dynamic

@property有两个对应的词,一个是@synthesize,一个是@dynamic。如果@synthesize和@dynamic都没写,那么默认的就是@syntheszie var = _var;

 @synthesize的语义是如果你没有手动实现setter方法和getter方法,那么编译器会自动为你加上这两个方法。

@dynamic诉编译器,属性的settergetter方法由用自己实现,不自生成。(当然对于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 [[[NSFileManagerdefaultManager] URLsForDirectory:NSDocumentDirectoryinDomains: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 = [[NSBundlemainBundle] URLForResource:@"CoreDatatest"withExtension:@"momd"];

    _managedObjectModel = [[NSManagedObjectModelalloc] 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 = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];

    NSURL *storeURL = [[selfapplicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDatatest.sqlite"];

    NSError *error =nil;

    NSString *failureReason =@"There was an error creating or loading the application‘s saved data.";

    if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:nilerror:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionarydictionary];

        dict[NSLocalizedDescriptionKey] =@"Failed to initialize the application‘s saved data";

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSErrorerrorWithDomain:@"YOUR_ERROR_DOMAIN"code:9999userInfo: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, [erroruserInfo]);

        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 = [selfpersistentStoreCoordinator];

    if (!coordinator) {

        returnnil;

    }

    _managedObjectContext = [[NSManagedObjectContextalloc] init];

    [_managedObjectContextsetPersistentStoreCoordinator:coordinator];

    return_managedObjectContext;

}


#pragma mark - Core Data Saving support


- (void)saveContext {

    NSManagedObjectContext *managedObjectContext =self.managedObjectContext;

    if (managedObjectContext !=nil) {

        NSError *error =nil;

        if ([managedObjectContexthasChanges] && ![managedObjectContextsave:&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, [erroruserInfo]);

            abort();

        }

    }

}

这些代码知道具体作用就好,如果想自己手动建立起来coredata文件,也可以自己手动写

下面就是在viewcontroller的具体操作,

先引入appdelegate和User,Department的头文件

viewcontroller里添加

@property (strong,nonatomic)AppDelegate *myAppDelegate;属性

然后,

具体操作,

添加:

    User*user = (User*)[NSEntityDescriptioninsertNewObjectForEntityForName:@"User"inManagedObjectContext:self.myAppDelegate.managedObjectContext];

    [user setName:_nametextfield.text];

    [user setAge:[NSNumbernumberWithInteger:[_agetextfield.textintegerValue]]];

    [user setSex:_sextextfield.text];

    NSError*error;

    BOOL isSaveSuccess = [myAppDelegate.managedObjectContextsave:&error];//保存(容易忘)

    if (!isSaveSuccess) {

        NSLog(@"Error:%@",error);

        _attentiontextview.text = [NSStringstringWithFormat:@"Error:%@",error];

    }else{

        NSLog(@"Save Successful!");

        _attentiontextview.text =@"Save Successful!";

    }

查询:

    //数据请求(请求):命令集

    NSFetchRequest*request = [[NSFetchRequestalloc]init];

    //NSEntityDescription(实体描述):表

    NSEntityDescription*user = [NSEntityDescriptionentityForName:@"Department"inManagedObjectContext:myAppDelegate.managedObjectContext];

    [request setEntity:user];

    NSError*error;

    NSArray*mutablefetchResult = [myAppDelegate.managedObjectContext

                                         executeFetchRequest:requesterror:&error];

    if (mutablefetchResult ==nil) {

        NSLog(@"Error: %@",mutablefetchResult);

    }

    NSLog(@"the count of entry:%lu",[mutablefetchResultcount]);

    NSString*str =@"";

    

    for (Department*userin mutablefetchResult) {

//        NSLog(@"name:%@------age:%@-------sex:%@",user.name,user.age,user.sex);

//        str = [str stringByAppendingFormat:@"name:%@------age:%@-------sex:%@ ---depart:%@\n",user.name,user.age,user.sex,user.userrelationship.departmentname];

        str = [str stringByAppendingFormat:@"name:%@------\n",user.departmentname];

    }

    NSLog(@"str:%@",str);

更新:

   //NSFetchRequest  数据请求(请求):命令集

    NSFetchRequest*request = [[NSFetchRequestalloc]init];

    //NSEntityDescription(实体描述):表

    NSEntityDescription*user = [NSEntityDescriptionentityForName:@"User"inManagedObjectContext:myAppDelegate.managedObjectContext];

    [request setEntity:user];

    //设置查询条件 NSPredicate(谓词):查询语句

    NSPredicate*predicate = [NSPredicatepredicateWithFormat:@"name == %@",@"lisi"];

    [request setPredicate:predicate];

    NSError*error;

    NSArray * mutablFetchResult = [myAppDelegate.managedObjectContextexecuteFetchRequest:request error:&error];

    if (mutablFetchResult ==nil) {

        NSLog(@"Error:%@",error);

        _attentiontextview.text = [NSStringstringWithFormat:@"Error:%@",error];

    }

    NSLog(@"the count of entry:%lu",[mutablFetchResultcount]);

    for (User*userin mutablFetchResult) {

        [user setAge:[NSNumbernumberWithInteger:999]];

    }

    //判断是否修改成功

    BOOL isSaveSuccess = [myAppDelegate.managedObjectContextsave:&error];//保存(容易忘)

    if (!isSaveSuccess) {

        NSLog(@"Error:%@",error);

        _attentiontextview.text = [NSStringstringWithFormat:@"Error:%@",error];

    }else{

        NSLog(@"update Successful!");

        _attentiontextview.text =@"update Successful!";

    }

删除:

 //数据请求(命令集)

    NSFetchRequest*request = [[NSFetchRequestalloc]init];

    //实体描述(表)

    NSEntityDescription*user = [NSEntityDescriptionentityForName:@"Department"inManagedObjectContext:myAppDelegate.managedObjectContext];

    [request setEntity:user];

    //设置查询条件

    NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"departmentname == %@",@"公共事业部"];

    [request setPredicate:predicate];

    NSError*error;

    NSArray*mutableFetchResult = [myAppDelegate.managedObjectContextexecuteFetchRequest:request error:&error];

    if (mutableFetchResult ==nil) {

        NSLog(@"Error:%@",error);

        _attentiontextview.text = [NSStringstringWithFormat:@"Error:%@",error];

    }

    NSLog(@"mutableFetchResult %lu",[mutableFetchResultcount]);

    for (User*userin mutableFetchResult) {

        [myAppDelegate.managedObjectContextdeleteObject:user];

    }

    //判断是否删除成功

    BOOL isDeleteSuccess = [myAppDelegate.managedObjectContextsave:&error];//保存(容易忘)

    if (!isDeleteSuccess) {

        NSLog(@"Error:%@",error);

        _attentiontextview.text = [NSStringstringWithFormat:@"Error:%@",error];

    }else{

        NSLog(@"delete Successful!");

        _attentiontextview.text =@"delete Successful!";

    }

当然了在主线程中进行这些操作不安全,可以另外开辟线程操作个人强烈推荐

http://blog.csdn.net/fengsh998/article/details/8111855

另外一篇coredata多线程安全

http://blog.csdn.net/chen505358119/article/details/9344389

第二部分coredata的利弊

coredata并非严格的说是对sqlite数据库的一个封装,也可以用其他的数据库,并不一定要使用sqlite3,当然了coredata的好处还是非常多的,高效,简介,能节省至少50%的代码量,条目清新

对于iOS开发者来说,会使用Core Data是一项必备技能。 没有它,很多app都不会存在。当在互联网上四处搜索Core Data学习教程,你很容易被各种各样的术语吓倒。事实上大部分学习教程都首先假定你已经知道了这些术语,而如果你不了解这些术语,那将会陷入困惑中。所以首先要知道关键的术语

下面这篇博文非常之好:

http://blog.jobbole.com/60025/

内容有点繁杂,冗余,诸位见谅则个


ios coredata的用法和利弊