CoreData使用

12045 ワード

一、CoreDataの簡単な使用
準備作業
  • データベース作成
  • 新規ファイル、CoreData->DataModel
  • を選択
  • エンティティ(テーブル)、Add Entity
  • を追加
  • 表に属性を追加し、Attributesの下の「+」番号
  • をクリックします.
  • モデルファイル
  • を作成する
  • 新規ファイル、CoreData->NSManaged Object subclass
  • を選択
  • ヒントに従ってエンティティ
  • を選択する.
  • コードを介して、関連するデータベースおよびエンティティ
    - (void)viewDidLoad {
       [super viewDidLoad];   /*
        *      ,           ,Coreadata     
        */
    
       // 1.    
       NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];   // 2.         
    
       // 2.1 model    
       NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];   // 2.2         
       //    ,          ,     
       NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];   // 2.3   CoreData         
       NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];   NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
       [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
    
       context.persistentStoreCoordinator = store;
       _context = context;
    
    }
  • CoreDataの基本操作(CURD)
  • 追加要素-Create
    -(IBAction)addEmployee{   //          
       //Employee *emp = [[Employee alloc] init];         
       Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
       emp.name = @"wangwu";
       emp.height = @1.80;
       emp.birthday = [NSDate date];   //        
       NSError *error = nil;
       [_context save:&error];   if (error) {       NSLog(@"%@",error);
       }
    }
  • データ読み出し-Read
      -(IBAction)readEmployee{      // 1.FetchRequest       
          NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];      // 2.      
          //   zhangsan
          NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",                          @"zhangsan"];
          request.predicate = pre;      // 3.    
          //        
          NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
          request.sortDescriptors = @[heigtSort];      // 4.    
          NSError *error = nil;      NSArray *emps = [_context executeFetchRequest:request error:&error];      if (error) {          NSLog(@"error");
          }      //NSLog(@"%@",emps);
          //    
          for (Employee *emp in emps) {          NSLog(@"   %@    %@    %@",emp.name,emp.height,emp.birthday);
          }
      }
  • 修正データ-Update
    -(IBAction)updateEmployee{   //   zhangsan    2m
    
       // 1.   zhangsan
       // 1.1FectchRequest       
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];   // 1.2      
       //   zhangsan
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"];
       request.predicate = pre;   // 1.3    
       NSArray *emps = [_context executeFetchRequest:request error:nil];   // 2.    
       for (Employee *e in emps) {
           e.height = @2.0;
       }   // 3.  
       NSError *error = nil;
       [_context save:&error];   if (error) {       NSLog(@"%@",error);
       }
    }
  • 削除データ-Delete
    -(IBAction)deleteEmployee{   //    lisi
    
       // 1.  lisi
       // 1.1FectchRequest       
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];   // 1.2      
       //   zhangsan
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",                       @"lisi"];
       request.predicate = pre;   // 1.3    
       NSArray *emps = [_context executeFetchRequest:request error:nil];   // 2.  
       for (Employee *e in emps) {
           [_context deleteObject:e];
       }   // 3.  
       NSError *error = nil;
       [_context save:&error];   if (error) {       NSLog(@"%@",error);
       }
    
    }
  • 二、CoreDataの表関連
    準備作業
  • データベース作成
  • 新規ファイル、CoreData->DataModel
  • を選択
  • エンティティ(表)、Add Entityを追加します.ここでは、関連付けに従って複数のエンティティ
  • を追加します.
  • 表に属性を追加し、Attributesの下の「+」番号
  • をクリックします.
  • モデルファイル
  • を作成する
  • 新規ファイル、CoreData->NSManaged Object subclass
  • を選択
  • ヒントに従ってエンティティを選択します.ここではまず関連するエンティティを選択し、最後に最上位のエンティティ
  • を追加します.
  • コードを介して、関連するデータベースおよびエンティティ
    - (void)viewDidLoad {
       [super viewDidLoad];   /*
        *      ,           ,Coreadata     
        */
    
       // 1.    
       NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];   // 2.         
    
       // 2.1 model    
       NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];   // 2.2         
       //    ,          ,     
       NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];   // 2.3   CoreData         
       NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];   NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
       [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
    
       context.persistentStoreCoordinator = store;
       _context = context;
    
    }
  • きほんそうさ
  • 追加要素-Create
    -(IBAction)addEmployee{   // 1.        ios android
       //1.1 iOS  
       Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
       iosDepart.name = @"ios";
       iosDepart.departNo = @"0001";
       iosDepart.createDate = [NSDate date];   //1.2 Android  
       Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
       andrDepart.name = @"android";
       andrDepart.departNo = @"0002";
       andrDepart.createDate = [NSDate date];   //2.          zhangsan  ios   lisi  android  
       //2.1 zhangsan
       Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
       zhangsan.name = @"zhangsan";
       zhangsan.height = @(1.90);
       zhangsan.birthday = [NSDate date];
       zhangsan.depart = iosDepart;   //2.2 lisi
       Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
       lisi.name = @"lisi";
       lisi.height = @2.0;
       lisi.birthday = [NSDate date];
       lisi.depart = andrDepart;   //3.      
       NSError *error = nil;
       [_context save:&error];   if (error) {       NSLog(@"%@",error);
       }
    }
  • 情報の読み出し-Read
    -(IBAction)readEmployee{   //   ios     
    
       // 1.FectchRequest       
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];   // 2.      
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"];
       request.predicate = pre;     // 4.    
       NSError *error = nil;   NSArray *emps = [_context executeFetchRequest:request error:&error];   if (error) {       NSLog(@"error");
       }   //    
       for (Employee *emp in emps) {       NSLog(@"   %@    %@",emp.name,emp.depart.name);
       }
    }
  • の他の機能は、前述の
  • に記載されていない前のいくつかと類似している.
    三、CoreDataのあいまいなクエリー
    準備作業は上記と似ていますが、主にクエリーの方法が異なります.
  • ファジイクエリ
    -(IBAction)readEmployee{   // 1.FectchRequest       
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];   // 2.    
       //          
       NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
       request.sortDescriptors = @[heigtSort];   // 3.    
       // 3.1    "wang"  //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];//    request.predicate = pre;
    
       //    "1"  //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];//    request.predicate = pre;
    
       //     "wu1"//    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];//    request.predicate = pre;
    
       // like   
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"];
       request.predicate = pre;   // 4.    
       NSError *error = nil;   NSArray *emps = [_context executeFetchRequest:request error:&error];   if (error) {       NSLog(@"error");
       }   //    
       for (Employee *emp in emps) {       NSLog(@"   %@    %@    %@",emp.name,emp.height,emp.birthday);
       }
    }
  • ページングクエリ
    -(void)pageSeacher{   // 1. FectchRequest       
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];   // 2.     
       //        
       NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
       request.sortDescriptors = @[heigtSort];   // 3.     
       //     15  
       //     6   
       //     0,6
       //     6,6
       //     12,6 3   
    
       // 3.1        
       request.fetchOffset = 12;   // 3.2      
       request.fetchLimit = 6;   // 4.     
       NSError *error = nil;   NSArray *emps = [_context executeFetchRequest:request error:&error];   if (error) {       NSLog(@"error");
       }   // 5.     
       for (Employee *emp in emps) {       NSLog(@"   %@    %@    %@",emp.name,emp.height,emp.birthday);
       }
    }
  • 四、複数のデータベースの使用
    注意:
    複数のデータベースを作成します.つまり、複数のDataModelのデータベースを作成します.1つのコンテキストに対応するにはbundle名に基づいてコンテキスト追加または読み取り情報を作成する必要があります.異なるコンテキストに基づいて、異なるエンティティにアクセスする必要があります.
  • 関連データベースおよびエンティティ
    - (void)viewDidLoad {
       [super viewDidLoad];   //             
       _companyContext = [self setupContextWithModelName:@"Company"];
       _weiboContext = [self setupContextWithModelName:@"Weibo"];
    }        
    
    /**
    *        ,       
    */-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{   // 1.    
       NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];   // 2.         
       // 2.1 model    
    
       //   :         ,   bundles nil   bundles                  
       //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    
       //          :
       NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];   NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];   // 2.2         
       //    ,          ,     
       NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];   // 2.3   Coredata         
       NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];   NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];   NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
    
       [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
    
       context.persistentStoreCoordinator = store;   // 3.      
       return context;
    }
  • 追加要素
    -(IBAction)addEmployee{   // 1.     
       Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];
       emp.name = @"zhagsan";
       emp.height = @2.3;
       emp.birthday = [NSDate date];   //        
       [_companyContext save:nil];   // 2.    
       Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
    
       status.text = @"      !";
       status.createDate = [NSDate date];
    
       [_weiboContext save:nil];
    }