CoreData基礎

 Core Data數據持久化是對SQLite的一個升級,它是ios集成的,在說Core Data以前,咱們先說說在CoreData中使用的幾個類。
   (1)managed object model(被管理的對象模型)
            是描述應用程序的數據模型,這個模型包含實體(Entity),特性(Property),讀取請求(Fetch Request)等。
    (2) managed object context(被管理的對象上下文)
         操做實際內容, 參與對數據對象進行各類操做的全過程,並監測數據對象的變化,以提供對 undo/redo 的支持及更新綁定到數據的 UI。
        做用:插入數據  查詢  更新  刪除
  (3)persistent store coordinator(持久化存儲助理)
           至關於數據文件管理器,處理底層的對數據文件的讀取與寫入。通常咱們無需與它打交道。
    (4)NSFetchRequest(獲取數據的請求)
        至關於查詢語句
     (5)NSPredicate(至關於查詢條件)
    (6)NSEntityDescription(實體結構)
    (7)後綴名爲.xcdatamodel的包
        裏面的.xcdatamodel文件,用數據模型編輯器編輯
編譯後爲.momd,這就是爲何文件中沒有.xcdatamodel的緣由,而咱們的程序中用到這個東西而不會報錯的緣由
數據存儲(data store)
Core Data支持4中類型的數據存儲:SQLiteStore, XMLStore, BinaryStore, InMemoryStore。
 
1、CoreData使用過程
一、建立CoreData文件(.xcdatamodelmodel.xcdatamodeld編譯以後會變成model.momd
建立CoreData文件,能夠在建立項目的時候勾選「create CoreData」,或者本身手動添加
二、將Entity轉成類
導出效果:
 
//-----------------------------------------model介紹---------------------------------------------
Model class
模型有點像數據庫的表結構,裏面包含Entry,實體又包含三種Property(特性):
Attribute(屬性)
RelationShip(關係)
Fetched Property(讀取屬性)。
Model class的名字多以 "Description" 結尾。咱們能夠看出:模型就是描述數據類型以及其關係的。
Managed Object Model
NSManagedObjectModel
數據模型
Entity                                                                                    NSEntityDescription 抽象數據類型,至關於數據庫中的表
Property                                                     NSPropertyDescription Entity 特性,至關於數據庫表中的一列
  > Attribute                                                              NSAttributeDescription 基本數值型屬性(如Int16, BOOL, Date等類型的屬性)
  > Relationship NSRelationshipDescription 屬性之間的關係
  > Fetched Property NSFetchedPropertyDescription 查詢屬性(至關於數據庫中的查詢語句)

1Entity - NSEntityDescription
Entity 至關於數據庫中的一個表,它描述一種抽象數據類型,其對應的類爲 NSManagedObject 或其子類。

NSEntityDescription 經常使用方法:
+insertNewObjectForEntityForName:inManagedObjectContext: 工廠方法,根據給定的Entity描述,生成相應的NSManagedObject對象,並插入 ManagedObjectContext 中。
-managedObjectClassName:返回映射到EntityNSManagedObject類名
-attributesByName:以名字爲key返回Entity中對應的Attributes
-relationshipsByName:以名字爲key返回Entity中對應的Relationships
 
2Property - NSPropertyDescription
PropertyEntity的特性,它至關於數據庫表中的一列,或者XML文件中的value-key對中的key。它能夠描述實體數據(Attribute)Entity之間的關係(RelationShip),或查詢屬性(Fetched Property)

> Attribute - NSAttributeDescription
Attribute 存儲基本數據,如 NSString, NSNumber or NSDate 等。它能夠有默認值,也可使用正則表達式或其餘條件對其值進行限定。一個屬性能夠是 optional 的。

> Relationship - NSRelationshipDescription
Relationship 描述 EntityProperty 之間的關係,能夠是一對一,也能夠是一對多的關係。

> Fetched Property - NSFetchedPropertyDescription
Fetched Property 根據查詢謂詞返回指定 Entity 的符合條件的數據對象。
 
//-----------------------------------------使用過程---------------------------------------------
 
手寫配置CoreData的對象:
@property (strongnonatomic)NSManagedObjectContext *context;
 
- (void)viewDidLoad {
    [super viewDidLoad];
    //準備工做:建立core data所須要的全部類對象,以及他們之間的關係
建立持久化存儲協調器(助理)
    //momdmodel.xcdatamodeld編譯以後會變成model.momd
    //1.1 建立模型對象的url
    NSURL *modelURL = [[NSBundle mainBundleURLForResource:@"Model" withExtension:@"momd"];
    //1.2 建立被管理對象模型
    NSManagedObjectModel *objectModel = [[NSManagedObjectModel allocinitWithContentsOfURL:modelURL];
   
真正建立持久化存儲協調器對象,並和被管理對象進行綁定
    NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator allocinitWithManagedObjectModel:objectModel];
//3.1 由持久化存儲協調器對象建立建立出持久化存儲對象(真正用來存儲數據的路徑)
    //獲取沙盒Documents路徑
    NSString *docmentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMaskYESlastObject];
    //拼接真正的sqlite文件路徑
    NSString *sqlitePath = [docmentPath stringByAppendingPathComponent:@"Model.sqlite"];
    NSURL *sqliteURL = [NSURL fileURLWithPath:sqlitePath];
   
    NSLog(@"sqlite路徑是:%@", sqlitePath);
    NSError *error = nil;
//注:可使用匿名方法(並且是推薦使用)
    NSPersistentStore *store = [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqliteURL options:nil error:&error];
     if (!store) {
        NSLog(@"error: %@",[error userInfo]);
    }
  建立被管理對象上下文
    self.context = [[NSManagedObjectContext allocinit];
//將建立好的持久化存儲協調器和被管理上下文進行綁定
    [self.context setPersistentStoreCoordinator:storeCoordinator];
}
//------------------------------------------------------系統自動配置-----------------------------------------------
在建立項目的時候,勾選Use CoreData,系統會自動配置CoreData的對象。
由於咱們可使用的就是上下文,所以獲取上下文對象就能夠了
//被管理對象上下文屬性
@property (nonatomicstrongNSManagedObjectContext *managedObjectContext;
//使用懶加載的方式獲取被管理對象上下文
- (NSManagedObjectContext *)managedObjectContext {
    //若是對象爲空
    //獲取當前程序的app單例對象:[UIApplication sharedApplication]
    //獲取當前程序的delegate單例對象:[[UIApplication sharedApplication] delegate]
    if (!_managedObjectContext) {
        AppDelegate *delegate = [[UIApplication sharedApplicationdelegate];
        //delegate單例對象的上下文屬性,賦值給當前類的上下文對象
        _managedObjectContext = delegate.managedObjectContext;
    }
    return _managedObjectContext;
}
//------------------------------------------------------End------------------------------------------------------
//插入一條數據
- (IBAction)insertItem {
    //sql語句insert into person (name, age, height) values ('bob', 19, 1.85);
    //1.返回一個給定Entity和被管理對象上下文的空的實體對象
    PersonModel * person = [NSEntityDescription insertNewObjectForEntityForName:@"PersonModel" inManagedObjectContext:self.context];
   
    //2.將上面返回的空的實體對象進行賦值
    person.name @"Bob";
    person.age @21;
    person.height @1.85;
   
    //3. 使用被管理對象上下文來執行插入動做(save:真正的將數據寫入數據庫文件中:Model.sqlite)
    NSError *error = nil;
    [self.context save:&error];
   
    if (error) {
        NSLog(@"插入數據失敗,失敗緣由是:%@", error);
    }
}
相關文章
相關標籤/搜索