xcode8使用coredata

昨晚突然有個(gè)朋友問(wèn)起coredata的使用,后來(lái)便自己寫了個(gè)demo看看,發(fā)現(xiàn)跟Xcode7使用有些不一樣,今天有時(shí)間就記下來(lái)跟大家分享下。
創(chuàng)建工程時(shí)勾選use core data

勾選use core data

打開(kāi)工程時(shí)會(huì)發(fā)現(xiàn)比多一個(gè).xcdatamodeld文件,名字和工程名一致,demo工程名為CoreDataDemo。

.xcdatamodeld文件

選中該文件 點(diǎn)擊add Entity 可創(chuàng)建實(shí)體,需大寫開(kāi)頭,可以理解為model,同時(shí)可添加屬性,選擇屬性類型

創(chuàng)建Entity ,添加屬性

然后就是Xcode8之后的差異了。
第一個(gè)圖是之前新建一個(gè)file,NSManagedObjectSubclass。
第二個(gè)截圖是現(xiàn)在Xcode的界面,取消了NSManagedObjectSubclass。


之前創(chuàng)建NSManagedObjectSubclass文件方式
NSManagedObjectSubclass文件取消

選中創(chuàng)建的Entity,點(diǎn)擊導(dǎo)航欄的Editor-->Create NSManagedObjectSubclass,然后按照提示操作下去,會(huì)生成四個(gè)文件


新建NSManagedObjectSubclass文件

生成的NSManagedObjectSubclass文件

細(xì)心的小伙伴可能還會(huì)發(fā)現(xiàn)AppDelegate跟平時(shí)我們創(chuàng)建的有些不同,多了一個(gè)coredata操作對(duì)象及方法。

//
//  AppDelegate.h
//  CoreDataDemo
//
//  Created by simon on 2017/5/3.
//  Copyright ? 2017年 simon. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong) NSPersistentContainer *persistentContainer;

- (void)saveContext;


@end

那我們現(xiàn)在來(lái)寫個(gè)增刪改查的操作。

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "Dog+CoreDataClass.h"


@interface ViewController ()
{
   AppDelegate *_app;
}
@end

- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.
   _app = (AppDelegate *)[UIApplication sharedApplication].delegate;
  [self createBtns];
}

- (void)createBtns{
   NSArray *titles = @[@"增",@"刪",@"改",@"查"];
   for (int i = 0; i < titles.count; i++) {
       UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
       btn.frame = CGRectMake(30 + i * 60, 100, 40, 40);
       [btn setTitle:titles[i] forState:UIControlStateNormal];
       [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
       [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
       btn.tag = i;
       [self.view addSubview:btn];
   }
}

- (void)btnAction:(UIButton *)btn{
   switch (btn.tag) {
       case 0:
           [self addCoreData];
           break;
       case 1:
           [self deleteCoreData];
           break;
       case 2:
           [self updateCoreData];
           break;
       case 3:
           [self selectCoreData];
           break;
           
       default:
           break;
   }
}

增加一條數(shù)據(jù):

- (void)addCoreData{
   Dog *dog = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
   static NSInteger index = 0;
   dog.name = [NSString stringWithFormat:@"tom%ld",index++];
   dog.sex = @"公";
   dog.age = [NSString stringWithFormat:@"%uyears",arc4random() % 15];
   [_app saveContext];
}

查詢所有數(shù)據(jù):

- (void)selectCoreData{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest :request error:nil];
    for (Dog *dog in array) {
        NSLog(@"dog name:%@",dog.name);
    }
} 

如需條件查詢可使用 NSPredicate 添加查詢條件。

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
    request.predicate = predicate;

刪除一條數(shù)據(jù):

- (void)deleteCoreData{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
    request.predicate = predicate;

    NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
    if (array.count) {
        for (Dog *dog in array) {
            [_app.persistentContainer.viewContext deleteObject:dog];
        }
        NSLog(@"DELETE SUCCESS!!");
    } else
        NSLog(@"NOT FOUND DATA");
}

更新某條數(shù)據(jù):

- (void)updateCoreData{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
    request.predicate = predicate;
    
    NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
    if (array.count) {
        for (Dog *dog in array) {
            dog.name = @"jerry8";
        }
        [_app saveContext];
        NSLog(@"UPDATA SUCCESS!!");
    } else
        NSLog(@"NOT FOUND DATA");
}

順便問(wèn)下,用chrome訪問(wèn)簡(jiǎn)書,用markdown模式寫這些字,chrome崩潰十幾次了,輸入文字就崩,不知道是不是添加高亮代碼塊的鍋,有沒(méi)有大神遇到過(guò)!(后來(lái)這些字都是在文本編輯器寫好貼上去的)
參考:http://www.lxweimin.com/p/337872d95727

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容