美文网首页
iOS数据持久化(三)--- CoreData

iOS数据持久化(三)--- CoreData

作者: 墨凌风起 | 来源:发表于2017-05-24 12:01 被阅读20次

    第1步:首先在创建项目的时候必须把Use Core Data 选上


    屏幕快照 2017-05-24 下午12.29.10.png

    1.1 新建的工程就会有一个Coredata.xcdatamodeld文件


    屏幕快照 2017-05-24 下午12.33.09.png

    1.2如果忘记选User Core Data,还可以另外创建一个.xcdatamodeld文件


    屏幕快照 2017-05-24 下午2.22.33.png

    第2步 创建实体


    屏幕快照 2017-05-27 下午7.13.04.png

    2.1创建实体关联的操作对象
    /注意/
    xcode8.0后 自定义的实体关联的操作对象默认swift语言更改

    屏幕快照 2017-07-08 下午6.16.56.png
    屏幕快照 2017-05-27 下午7.21.42.png 屏幕快照 2017-05-27 下午7.24.39.png 屏幕快照 2017-05-27 下午7.24.53.png

    2.2然后就会生成四个文件

    屏幕快照 2017-05-27 下午7.27.16.png

    第3步:新建一个单例 StudentManager
    StudentManager.h文件:

    #import <Foundation/Foundation.h>
    #import "Student+CoreDataProperties.h"
    #import "User.h"
    @interface StudentManager : NSObject
    
    @property(nonatomic, strong) User *user;
    +(id)shareInstance;
    //添加数据
    #if 0
    -(Student *)insertData:(NSDictionary *)stu;
    #else
    -(Student *)insertData:(User *)user;
    #endif
    
    //删除数据
    -(BOOL)deleteDataWithName:(NSString *)name;
    
    //查找数据
    -(Student *)qureyDataWithName:(NSString *)name;
    
    //改动数据
    -(BOOL)upadateDataWithNewData:(User *)newUser OldName:(NSString *)oldName;
    
    //加载整个存储的数据源
    -(NSArray *)loadAllData;
    @end
    

    StudentManager.m文件:

    #import "StudentManager.h"
    #import "AppDelegate.h"
    @implementation StudentManager
    
    +(id)shareInstance{
        static StudentManager *studentManager;
        static dispatch_once_t onceTonken;
        dispatch_once(&onceTonken, ^{
            studentManager = [[StudentManager alloc]init];
            
        });
        return studentManager;
    }
    -(AppDelegate *)delegate{
        return (AppDelegate *)[[UIApplication sharedApplication] delegate];
    }
    
    #if 0
    #pragma mark --- 添加数据  字典形式
    -(Student *)insertData:(NSDictionary *)dict{
        NSError *error;
        NSManagedObjectContext *managerContext = [self delegate].persistentContainer.viewContext;
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:managerContext];
        Student *yonger = [(Student *)[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:managerContext];
        
        NSLog(@"++++%@",dict);
        yonger.name = dict[@"name"];
        yonger.age = dict[@"age"] ;
        yonger.phone = dict[@"phone"];
        
        BOOL result = [[self delegate].persistentContainer.viewContext save:&error];
        if (result) {
            return yonger;
        }
        return nil;
    }
    #else
    -(Student *)insertData:(User *)user{
        NSError *error;
        NSManagedObjectContext *managerContext = [self delegate].persistentContainer.viewContext;
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:managerContext];
        Student *yonger = [(Student *)[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:managerContext];
        
        NSLog(@"++++%@",user.name);
        yonger.name = user.name;
        yonger.age = user.age ;
        yonger.phone = user.phone;
        
        BOOL result = [[self delegate].persistentContainer.viewContext save:&error];
        if (result) {
            return yonger;
        }
        return nil;
    }
    #endif
    -(NSArray *)loadAllData{
        //创建请求
        NSFetchRequest *request = [[NSFetchRequest alloc]init];
        //设置需要查询的实体对象
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[self delegate].persistentContainer.viewContext];
        //设置请求实体
        [request setEntity:entity];
        NSError *error = nil;
        NSArray *infos = [[[self delegate].persistentContainer.viewContext executeFetchRequest:request error:&error] mutableCopy];
        if (!error) {
            return infos;
        }
        return nil;
    }
    //删除 根据姓名删除
    -(BOOL)deleteDataWithName:(NSString *)name{ 
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",name];
        NSFetchRequest *request = [[NSFetchRequest alloc]init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[self delegate].persistentContainer.viewContext];
        [request setEntity:entity];
        [request setPredicate:predicate];
        [request setFetchLimit:1];
        NSError *error = nil;
        NSArray *infos = [[[self delegate].persistentContainer.viewContext executeFetchRequest:request error:&error] mutableCopy];
        if (infos == nil) {
            return NO;
        }
        for (Student *stu in infos) {
            [[self delegate].persistentContainer.viewContext deleteObject:stu];
            [[self delegate].persistentContainer.viewContext save:&error];
        }
       
        return NO;
    }
    //查询
    -(Student *)qureyDataWithName:(NSString *)name{
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",name];
        NSFetchRequest *request = [[NSFetchRequest alloc]init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[self delegate].persistentContainer.viewContext];
        [request setEntity:entity];
        [request setPredicate:predicate];
        [request setFetchLimit:1];
        NSError *error = nil;
        NSArray *infos = [[[self delegate].persistentContainer.viewContext executeFetchRequest:request error:&error] mutableCopy];
        if (infos == nil) {
            NSLog(@"查找不到");
            return nil;
        }
        for (Student *stu in infos) {
            
            return stu;
        }
        return nil;
    }
    //更新
    -(BOOL)upadateDataWithNewData:(User *)newUser OldName:(NSString *)oldName{
        NSError *error;
        //先查找旧数据
        Student *oldstudent = [self qureyDataWithName:oldName];
        oldstudent.name = newUser.name;
        oldstudent.age = newUser.age;
        oldstudent.phone = newUser.phone;
        
        BOOL result = [[self delegate].persistentContainer.viewContext save:&error];
        if (result) {
            NSLog(@"更新成功");
            return YES;
        }
        NSLog(@"修改不成功");
        return NO;
        
    }
    @end
    

    注解:添加数据用了两种方法,一种是将要操作的数据属性放在字典中进行传送,一种是用一个数据模型user传送。user模型如下,如果要用字典传送就不需要
    user.h

    #import <Foundation/Foundation.h>
    @interface User : NSObject
    @property (nonatomic, copy) NSString *age;
    @property (nonatomic, copy) NSString *phone;
    @property (nonatomic, copy) NSString *name;
    @end
    

    user.m

    #import "User.h"
    @implementation User
    /*
      User 可以作为一个数据模型model,如果不用user,我们在保存,查找,删除数据是对数据的传递只能以字典的方式进行,将数据的各个属性挨个保存在dictionary的相应键值中,然后再取出来
     user模型 可避免在传递过程中认为的遗漏数据的某个属性,应为user是以一个数据对象的整体来进行传递的
     #if X
            X=1时执行
     #else 
            X=0时执行
     #endif
     
     */
    -(NSString *)name{
        if (!_name) {
            _name = @"";
        }
        return _name;
    }
    
    -(NSString *)age{
        if (!_age) {
            _age = @"";
        }
        return _age;
    }
    
    -(NSString *)phone{
        if (!_phone) {
            _phone = @"";
        }
        return _phone;
    }
    @end
    

    源代码见:CoreData增删改查

    相关文章

      网友评论

          本文标题:iOS数据持久化(三)--- CoreData

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