CoreData編程

另一個(gè)常用數(shù)據(jù)庫:realm

創(chuàng)建支持CoreData的應(yīng)用


第一步.png

CoreData支持可視化的創(chuàng)建數(shù)據(jù)模型


第二步.png

每一個(gè)實(shí)體(Entity)對應(yīng)一個(gè)model類
第三步.png

給實(shí)體添加屬性,對應(yīng)數(shù)據(jù)庫中的字段


第四步.png
保存數(shù)據(jù)
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    //獲取管理上下文, 可以理解為"數(shù)據(jù)庫"
    //Xcode版本以前用: NSManagedObjectContext *context =appDelegate.managedObjectContext;
    NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
    //使用實(shí)體名稱創(chuàng)建一個(gè)實(shí)體(描述對象)
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
    //使用實(shí)體描述創(chuàng)建管理對象,并且插入管理上下午("數(shù)據(jù)庫"),并沒有持久化
    NSManagedObject *student = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
    [student setValue:@"張三" forKey:@"name"];
    [student setValue:@22 forKey:@"age"];
    [student setValue:@"長沙" forKey:@"address"];
    //持久化(保存)
    if ([context save:nil]) {
        NSLog(@"save success");
    }
獲取數(shù)據(jù)
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
    //使用實(shí)體名創(chuàng)建數(shù)據(jù)請求對象
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    //執(zhí)行數(shù)據(jù)請求
    NSArray *arr = [context executeFetchRequest:request error:nil];
    NSLog(@"----->%@", arr);

創(chuàng)建NSManagedObject子類

1.png

2.png
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
    Student *student = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
    //存
    student.name = @"張三";
    student.age = 31;
    student.address = @"長沙";
    if ([context save:nil]) {
        NSLog(@"保存成功");
    }
    //取
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    NSArray *arr = [context executeFetchRequest:request error:nil];
    for (Student *stu in arr) {
        NSLog(@"------->%@: %hd", stu.name, stu.age);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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