美文网首页
xcode8使用coredata

xcode8使用coredata

作者: Simon_____ | 来源:发表于2017-05-04 14:56 被阅读0次

    昨晚突然有个朋友问起coredata的使用,后来便自己写了个demo看看,发现跟Xcode7使用有些不一样,今天有时间就记下来跟大家分享下。
    创建工程时勾选use core data

    勾选use core data

    打开工程时会发现比多一个.xcdatamodeld文件,名字和工程名一致,demo工程名为CoreDataDemo。

    .xcdatamodeld文件

    选中该文件 点击add Entity 可创建实体,需大写开头,可以理解为model,同时可添加属性,选择属性类型

    创建Entity ,添加属性

    然后就是Xcode8之后的差异了。
    第一个图是之前新建一个file,NSManagedObjectSubclass。
    第二个截图是现在Xcode的界面,取消了NSManagedObjectSubclass。


    之前创建NSManagedObjectSubclass文件方式 NSManagedObjectSubclass文件取消

    选中创建的Entity,点击导航栏的Editor-->Create NSManagedObjectSubclass,然后按照提示操作下去,会生成四个文件


    新建NSManagedObjectSubclass文件
    生成的NSManagedObjectSubclass文件

    细心的小伙伴可能还会发现AppDelegate跟平时我们创建的有些不同,多了一个coredata操作对象及方法。

    //
    //  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
    

    那我们现在来写个增删改查的操作。

    #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;
       }
    }
    

    增加一条数据:

    - (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];
    }
    

    查询所有数据:

    - (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;
    

    删除一条数据:

    - (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");
    }
    

    更新某条数据:

    - (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");
    }
    
    

    顺便问下,用chrome访问简书,用markdown模式写这些字,chrome崩溃十几次了,输入文字就崩,不知道是不是添加高亮代码块的锅,有没有大神遇到过!(后来这些字都是在文本编辑器写好贴上去的)
    参考:http://www.jianshu.com/p/337872d95727

    相关文章

      网友评论

          本文标题:xcode8使用coredata

          本文链接:https://www.haomeiwen.com/subject/wfnrtxtx.html