coreData

#import "ViewController.h"
#import "Husband.h"
#import "Wife.h"
@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
#pragma mark - 上下文
    // 從應用程序包中加載模型文件
    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    // 傳入模型對象,初始化NSPersistentStoreCoordinator
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    // 初始化上下文
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    // 設置上下文的persistentStoreCoordinator屬性
    context.persistentStoreCoordinator = psc;
#pragma mark - 持久化存儲庫
    // 構建SQLite數據庫文件的路徑
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"model.data"];
    // 將數據庫路徑轉成URL
    NSURL *url = [NSURL fileURLWithPath:filePath];
    // 添加持久化存儲庫,這里使用SQLite作為存儲庫
    NSError *error = nil;
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    // 判斷數據庫是否添加成功
    if (store == nil) {
        [NSException raise:@"添加數據庫錯誤" format:@"%@", [error localizedDescription]];
    }

@end
#pragma mark - 添加數據
    // 創建一個Husband實體對象,傳入上下文
    Husband *husband = [NSEntityDescription insertNewObjectForEntityForName:@"Husband" inManagedObjectContext:context];
    // 通過鍵值編碼的方式設置Husband的name屬性
    [husband setValue:@"jack" forKey:@"name"];
    // 通過coredata生成的實體類來創建一個Wife實體對象,傳入上下文
    Wife *wife = [NSEntityDescription insertNewObjectForEntityForName:@"Wife" inManagedObjectContext:context];
    // 通過setter方法設置屬性
    wife.name = @"rose";
    // 設置Husband和Wife之間的關聯關系(一方關聯,另一方自動關聯)
    wife.husband = husband;
    // 利用上下文對象,將數據同步到持久化存儲庫
    BOOL success = [context save:&error];
    if (!success) {
        [NSException raise:@"訪問數據庫錯誤" format:@"%@", [error localizedDescription]];
    }
#pragma mark - 刪除數據
    // 初始化一個查詢請求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    // 設置要查詢的實體
    request.entity = [NSEntityDescription entityForName:@"Husband" inManagedObjectContext:context];
    // 設置條件過濾(搜索name等于jack2的實體)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", @"jack2"];
    request.predicate = predicate;
    // 執行請求,返回一個數組
    NSArray *objs = [context executeFetchRequest:request1 error:&error];
    if (error) {
        [NSException raise:@"查詢錯誤" format:@"%@", [error localizedDescription]];
    }
#pragma mark - 查詢數據
    // 初始化一個查詢請求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    // 設置要查詢的實體
    request.entity = [NSEntityDescription entityForName:@"Husband" inManagedObjectContext:context];
    // 設置排序(按照name降序)
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 設置條件過濾(搜索name中包含字符串"ja"的記錄)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*ja*"];
    request.predicate = predicate;
    // 執行請求,返回一個數組
    NSArray *objs = [context executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查詢錯誤" format:@"%@", [error localizedDescription]];
    }
    // 遍歷數據
    for (NSManagedObject *obj in objs) {
        NSLog(@"name = %@", [obj valueForKey:@"name"]);
        // 實體屬性中包含另一個實體,不需要再次設置查詢請求,Core Data會根據關聯關系查詢到關聯的實體信息
        NSLog(@"wife = %@", [[obj valueForKey:@"wife"] valueForKey:@"name"]);
    }

轉載于:宏創學院

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容