數(shù)據(jù)處理之CoreData

  • CoreData數(shù)據(jù)持久化框架是Cocoa API的一部分,首次在iOS5版本中出現(xiàn),它允許按照實體-屬性-值模式組織數(shù)據(jù),并以XML,二進制文件或者SQLite數(shù)據(jù)文件的格式持久化數(shù)據(jù).
  • CoreData主要提供的對象-關系映射(ORM)功能,把OC對象轉(zhuǎn)化為數(shù)據(jù)保存到文件,也可以數(shù)據(jù)轉(zhuǎn)化為OC對象
CoreData和SQLite的比較
  • SQLite
    1 基于C接口,需要使用sql語句,代碼繁瑣
    2 在處理大量數(shù)據(jù)時,表關系更直觀
    3 在OC中是不是可視化的
  • CoreData
    1 可視化,有undo/redo能力
    2 可以實現(xiàn)多種文件格式 NSSQLiteStoreType,NSBinaryStoreType,NSInMemoryStore Type,NSXMLStoreType.
    3.蘋果官方API支持,與iOS結(jié)合更緊密
CoreData核心對象
  • NSManagedObjectContext 數(shù)據(jù)管理器器類(負責應用和數(shù)據(jù)庫之間的交互)
  • NSManagedObjectModel 數(shù)據(jù)模型器類(當對于可視化創(chuàng)建model的基類)
  • NSPersistentStoreCoordinator 數(shù)據(jù)協(xié)調(diào)器類 (添加持久化數(shù)據(jù)庫)
  • NSEntityDescription 實體描述類(用來描述實體類)
CoreData數(shù)據(jù)庫框架的核心對象
  • NSPersistentStore:持久化存儲,一個被封裝好的底層類,用于存儲數(shù)據(jù)
  • 存儲文件:用來存儲和管理數(shù)據(jù)的文件
    1 NSSQLiteStoreType
    2 NSBinaryStoreType
    3 NSInMemoryStoreType
    4 NSXMLStoreType.
  • NSManagedObjectContext:被管理對象上下文CoreData中用于操作和使用數(shù)據(jù),負責應用和數(shù)據(jù)庫之間的交互
    1 數(shù)據(jù)的保存需要NSManagedObjectContext進行save操作
    2 數(shù)據(jù)的查詢需要NSManagedObjectContext進行executeFetchRequest操作(返回值是數(shù)組)
    3 CoreData提供的是對象關系映射,NSManagedObjectContext操作的都是NSManagedObject對象
  • NSManagedObjectMode:被管理對象對象模型,管理多個對象
  • NSManagedObject:被管理對象,CoreData返回的數(shù)據(jù)模型,被管理的對象是根據(jù)實體描述生成的
  • NSEntityDescription:實體描述類,根據(jù)實體創(chuàng)建被管理對象
  • Entity:實體類,實體是對象文件數(shù)據(jù)的描述,被管理對象表示實體,實體包含名稱,屬性(字段)和關系,實體的名稱通常和被管理對象名一致
  • NSFetchRequest:查詢請求,NSManagedObjectContext根據(jù)NSFetchRequest查詢數(shù)據(jù),以數(shù)組形式返回,數(shù)組中包含被管理對象(NSManagedObject)
  • NSSortDescriptor:排序操作

CoreData數(shù)據(jù)庫的簡單操作

第一步:添加AppDelegate頭文件

#import "AppDelegate.h"

第二步:通過單例方法獲取協(xié)議
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
第三步:創(chuàng)建實體對象
//.創(chuàng)建實體對象(也就是具體對那個表進行操作)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:delegate.managedObjectContext];
第四步:增刪查改
/**增**/
//在創(chuàng)建的時候要使用coreData提供的方法,這樣數(shù)據(jù)管理器就可以管理此數(shù)據(jù)了
Person *person = [[Person alloc] initWithEntity:entity insertIntoManagedObjectContext:delegate.managedObjectContext];
//同步到數(shù)據(jù)庫
    person.name = @"張三";
    person.sex = @"nan";
    person.age = 12;
    [delegate saveContext];

/**刪**/
//    創(chuàng)建請求體
NSFetchRequest *request1 = [[NSFetchRequest alloc] init];
//    //請求需要的具體實體
request1.entity = entity;
//    //創(chuàng)建請求條件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 1"];
request1.predicate = predicate;
NSArray *array1 = [delegate.managedObjectContext executeFetchRequest:request1 error:nil];
for (Person *person2 in array1) {
    [delegate.managedObjectContext deleteObject:person2];
    NSLog(@"%@",person2.name);
}
[delegate saveContext];

/**查**/
//創(chuàng)建請求體
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//請求體需要的具體實體
request.entity = entity;
NSArray *array = [delegate.managedObjectContext executeFetchRequest:request error:nil];
for (Person *person1 in array) {
    NSLog(@"%@",person1.name);
    NSLog(@"%p",person1);
}

/**改**/
//創(chuàng)建請求體
NSFetchRequest *request2 = [[NSFetchRequest alloc] init];
request2.entity = entity;
//創(chuàng)建請求條件
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name = %@",@"張三"];
request2.predicate = predicate1;
NSArray *array2 = [delegate.managedObjectContext executeFetchRequest:request2 error:nil];
for (Person *person3 in array2) {
    person3.name = @"李四";
    NSLog(@"%@",person3.name);
}
[delegate saveContext];
AppDelegate中CoreData自帶的方法

<pre><code>- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "xalo.UI___CoreData" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains: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;
    }
    //獲取文件目錄路徑,momd是xcdatamodeld的簡寫
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"UI___CoreData" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
    }

  • (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
    }

    // Create the coordinator and store

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"UI___CoreData.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:@{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption:@YES} 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 {
    // 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 = [self persistentStoreCoordinator];
    if (!coordinator) {
    return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_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]) {
    // 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, [error userInfo]);
    abort();
    }
    }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容