zoukankan      html  css  js  c++  java
  • CoreData使用

    1.如果想创建一个带有coreData的程序,要在项目初始化的时候勾选中

    2.创建完成之后,会发现在AppDelegate里多出了几个属性,和2个方法 

    1. <span style="font-size:18px;">  
    2.   
    3. @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;  
    4. @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;  
    5. @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;  
    6.   
    7. - (void)saveContext;  
    8. - (NSURL *)applicationDocumentsDirectory;</span>  

    managedObjectContext (被管理的数据上下文)操作实际内容(操作持久层)作用:插入数据,查询数据,删除数据

     

    NSManagedObjectModel(被管理的数据模型)数据库所有表格或数据结构,包含各实体的定义信息 作用:添加实体的属性,建立属性之间的关系操作方法:视图编辑器,或代码

    NSPersistentStoreCoordinator(持久化存储助理)相当于数据库的连接器 作用:设置数据存储的名字,位置,存储方式,和存储时机

    方法saveContext表示:保存数据到持久层(数据库)

    方法applicationDocumentsDirectory表示:应用程序沙箱下的Documents目录路径

    3.如果想创建一个实体对象的话,需要点击.xcdatamodel,Add Entity,添加想要的字段

    4.生成对象文件,command+n,然后选中CoreData里的NSManagerObjectSubClass进行关联,选中实体创建

    5.添加数据 

    1. Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];  
    2.       
    3.     if (newPerson == nil){  
    4.         NSLog(@"Failed to create the new person.");  
    5.         return NO;  
    6.     }  
    7.       
    8.     newPerson.firstName = paramFirstName;  
    9.     newPerson.lastName = paramLastName;  
    10.     newPerson.age = [NSNumber numberWithUnsignedInteger:paramAge];  
    11.     NSError *savingError = nil;  
    12.       
    13.     if ([self.managedObjectContext save:&savingError]){  
    14.         return YES;  
    15.     } else {  
    16.         NSLog(@"Failed to save the new person. Error = %@", savingError);  
    17.     }  

    NSEntityDescription(实体结构)相当于表格结构

    6.取出数据查询 

    1. /* Create the fetch request first */  
    2.     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];  
    3.     /* Here is the entity whose contents we want to read */  
    4.     NSEntityDescription *entity =  
    5.     [NSEntityDescription  
    6.      entityForName:@"Person"  
    7.      inManagedObjectContext:self.managedObjectContext];  
    8.     /* Tell the request that we want to read the 
    9.      contents of the Person entity */  
    10.     [fetchRequest setEntity:entity];  
    11.     NSError *requestError = nil;  
    12.     /* And execute the fetch request on the context */  
    13.     NSArray *persons =  
    14.     [self.managedObjectContext executeFetchRequest:fetchRequest  
    15.                                              error:&requestError];  
    16.     /* Make sure we get the array */  
    17.     if ([persons count] > 0){  
    18.         /* Go through the persons array one by one */  
    19.         NSUInteger counter = 1;  
    20.         for (Person *thisPerson in persons){  
    21.             NSLog(@"Person %lu First Name = %@",  
    22.                   (unsigned long)counter,   
    23.                   thisPerson.firstName);   
    24.             NSLog(@"Person %lu Last Name = %@",   
    25.                   (unsigned long)counter,   
    26.                   thisPerson.lastName);  
    27.             NSLog(@"Person %lu Age = %ld",  
    28.                   (unsigned long)counter,  
    29.                   (unsigned long)[thisPerson.age unsignedIntegerValue]);  
    30.             counter++;  
    31.         }  
    32.     } else {  
    33.         NSLog(@"Could not find any Person entities in the context.");   
    34.     }  

    7.删除数据 
    1. /* Create the fetch request first */  
    2.     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];  
    3.     /* Here is the entity whose contents we want to read */  
    4.     NSEntityDescription *entity =  
    5.     [NSEntityDescription  
    6.      entityForName:@"Person"  
    7.      inManagedObjectContext:self.managedObjectContext];  
    8.     /* Tell the request that we want to read the 
    9.      contents of the Person entity */  
    10.     [fetchRequest setEntity:entity];  
    11.     NSError *requestError = nil;  
    12.     /* And execute the fetch request on the context */  
    13.     NSArray *persons =  
    14.     [self.managedObjectContext executeFetchRequest:fetchRequest  
    15.                                              error:&requestError];  
    16.     if ([persons count] > 0){  
    17.         /* Delete the last person in the array */  
    18.         Person *lastPerson = [persons lastObject];  
    19.         [self.managedObjectContext deleteObject:lastPerson];  
    20.         NSError *savingError = nil;  
    21.         if ([self.managedObjectContext save:&savingError]){  
    22.             NSLog(@"Successfully deleted the last person in the array.");  
    23.         } else {  
    24.             NSLog(@"Failed to delete the last person in the array.");  
    25.         }  
    26.     } else {   
    27.         NSLog(@"Could not find any Person entities in the context.");   
    28.     }   

    8.排序 
        NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];  
    
        NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];  
    
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:ageSort,firstNameSort, nil nil];  
    
        fetchRequest.sortDescriptors = sortDescriptors;
    
        //  注意 ascending:YES 属性决定排序顺序
    
  • 相关阅读:
    0_Simple__simplePrintf
    0_Simple__simplePitchLinearTexture
    0_Simple__simpleP2P
    0_Simple__simpleOccupancy
    0_Simple__MultiGPU
    0_Simple__simpleMultiCopy
    0_Simple__simpleMPI
    0_Simple__simpleLayeredTexture
    0_Simple__simpleCubemapTexture
    0_Simple__simpleCooperativeGroups
  • 原文地址:https://www.cnblogs.com/fuunnyy/p/5302491.html
Copyright © 2011-2022 走看看