coredata笔记2cook

来源:互联网 发布:ssl nginx 编辑:程序博客网 时间:2024/05/22 02:03
Persistent store

  The object that represents the actual data base on disk. We never use this object directly.

Persistent store coordinator
   The object that coordinates reading and writing of information from and to the persistent store. The coordinator is the bridge between the managed object context and the persistent store.
Managed object model (MOM)
   This is a simple file on disk that will represent our data model. Think about it as your database schema.
Managed object
   This class represents an entity that we want to store in Core Data. Traditional database programmers would know such entities as tables. A managed object is of type NSManagedObject, and its instances are placed on managed object contexts. They adhere to the schema dictated by the managed object model, and they get saved to a persistent store through a persistent store coordinator.
Managed object context (MOC)
   This is a virtual board. That sounds strange, right? But let me explain. We create Core Data objects in memory and set their properties and play with them. All this playing is done on a managed object context. The context keeps track of all the things that we are doing with our managed objects and even allows us to undo those actions. Think of your managed objects on a context as toys that you have brought on a table to play with. You can move them around, break them, move them out of the table, and bring new toys in. That table is your managed object context, and you can save its state when you are ready. When you save the state of the managed object context, this save operation will be communicated to the persistent store coordinator to which the context is connected, upon which the persistent store coordinator will store the information to the persistent store and subsequently to disk.

1.Creating a Core Data Model with Xcode




2.Generating Class Files for Core Data Entities

  使用NSManagedObject subclass新建子类,会生成Person.h and Person.m.

  现在新建和保存数据,模板

- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

                           Person *newPerson = [NSEntityDescription
                                                                insertNewObjectForEntityForName:@"Person"
                                                                               inManagedObjectContext:self.managedObjectContext];
                              if (newPerson != nil){
                                        newPerson.firstName = @"Anthony";
                                        newPerson.lastName = @"Robbins";
                                                 newPerson.age = @51;
                                                 NSError *savingError = nil;
                                                  if ([self.managedObjectContext save:&savingError]){
                                                                 NSLog(@"Successfully saved the context.");
                                                        } else {
                                                                NSLog(@"Failed to save the context. Error = %@", savingError);
                                                                     }
                                } else {
                                     NSLog(@"Failed to create the new person.");
                                           }

3.Reading Data from Core Data  

  参考代码

/* Tell the request that we want to read the
contents of the Person entity */
/* Create the fetch request first */
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
                                                                     initWithEntityName:@"Person"];
                                                         NSError *requestError = nil;
/* And execute the fetch request on the context */
                             NSArray*persons= [self.managedObjectCont

                                                            extexecuteFetchRequest:fetchRequest error:&requestError];
/* Make sure we get the array */
                                               if ([persons count] > 0){
/* Go through the persons array one by one */
                                                    NSUInteger counter = 1;
                                                           for (Person *thisPerson in persons){
                                                           NSLog(@"Person %lu First Name = %@",

                                                                                         (unsigned long)counter,thisPerson.firstName);
                                                           NSLog(@"Person %lu Last Name = %@",
                                                                                          (unsigned long)counter,thisPerson.lastName);
                                                           NSLog(@"Person %lu Age = %ld",
                                                     (unsigned long)counter,(unsigned long)[thisPerson.age unsignedIntegerValue]);
                                                               counter++;
                                                                       }
                                                                } else {
                                                                    NSLog(@"Could not find any Person entities in the context.");
                                                          }

4.Deleting Data from Core Data

    参考方式  [self.managedObjectContext deleteObject:lastPerson];


第一部分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 {

return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory 

                                               inDomains:NSUserDomainMask] lastObject];

}

//托管对象

- (NSManagedObjectModel *)managedObjectModel {

if (_managedObjectModel != nil) {

return _managedObjectModel;

}

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@CoreDatatest 

                                          withExtension:@momd];

_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

return _managedObjectModel;

}

//持久化存储协调器

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

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 {

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]) {

NSLog(@Unresolved error %@, %@, error, [error userInfo]);

abort();

}

}

}

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


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

先引入appdelegateUser,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!;

}




0 0
原创粉丝点击