coreData的使用

来源:互联网 发布:tensorflow有趣的项目 编辑:程序博客网 时间:2024/06/05 02:02
 1.#import <CoreData/CoreData.h>
 2.创建CoreData的数据模型文件(类似于数据库的创建表)
    这样托管对象模型知道所有当前工程中用到的托管对象的定义
    创建一个NSManagedObjectModel 数据模型文件
 
 //1.创建数据模型文件-》new file->core Data--》选中Data Model,创建文件 (User.xcdatamodeld)在里面创建 数据模型实例Entity(UserModel)
 //2.创建跟数据模型文件关联的数据模型类new file->core Data->选中 NSManagedObject of subclass --》关联上User.xcdatamodeld数据模型文件中的UserModel 实例
 //3.用代码初始化CoreData
 //3.1 导入 #import <CoreData/CoreData.h>
 //3.2 从沙盒包内 读取数据模型文件

 有两种方式:
 a.//获取到coreData文件的路径,并转换成url
 //在包内User.xcdatamodeld会转化为 User.momd
 
 NSString *coreDataPath  =[[NSBundle mainBundle] pathForResource:@"User" ofType:@"momd"];
 //加载coreData文件中的数据,转成model
 NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:coreDataPath]];
 
 b.NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
 中的nil表示连接项目中所有的 .xcdatamodeld 文件为一个datamodel,这是一个非常好的方法,把多个entity放在各自的xcodemodel文件中分开管理,然后用这个函数连接起来生成一个datamodel,这样就可以对应一个persistentStore。
//NSLog(@"data:%@",[[NSBundle mainBundle] pathForResource:@"User" ofType:@"momd"]);

//3.2获取 数据模型文件

3.创建协调器
NSPersistentStoreCoordinator

4.//将coreData数据映射到数据库
addPersistentStoreWithType

5.//创建上下文托管对象
NSManagedObjectContext

6增删改查

-------------------------------------------------------------

#import "RootViewController.h"
#import <CoreData/CoreData.h>
#import "UserModel.h"

@interface RootViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSManagedObjectContext *context;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *ageTF;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dataArray=[[NSMutableArray alloc] init];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self initCoreData];
}

#pragma mark - 初始化CoreData
-(void)initCoreData{
    //1、获取.xcdatamodeld  读成一个数据模型文件对象
#if 1
    NSManagedObjectModel *fileModel=[NSManagedObjectModel mergedModelFromBundles:nil];
#else
    NSString *path=[[NSBundle mainBundle] pathForResource:@"User" ofType:@"momd"];
    NSManagedObjectModel *fileModel=[[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
#endif
    
    //2、设置存储协调器
    //2.1.创建协调器,关联model
    NSPersistentStoreCoordinator *coordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:fileModel];
    //2.2.设置一个数据库存储的地址
    NSString *dataPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/myData.sqlite"];
    //2.3.设置数据存储类型(设置为数据库:NSSQLiteStoreType)
    NSError *error=nil;
    NSPersistentStore *store=[coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:&error];
    if (!store) {
        NSLog(@"%@",error.description);
    }
    
    //3、创建上下文管理对象(对数据库进行增删改查) 关联协调器
    self.context=[[NSManagedObjectContext alloc] init];
    self.context.persistentStoreCoordinator=coordinator;//设置协调器
}

- (IBAction)addClick:(id)sender {
    //增加一个数据模型对象,通过上下文去向数据库中添加UserModel对象
    UserModel *model=(UserModel *)[NSEntityDescription insertNewObjectForEntityForName:@"UserModel" inManagedObjectContext:self.context];
    model.name=self.nameTF.text;
    model.fName=[self.nameTF.text substringToIndex:1];
    model.age=@(self.ageTF.text.integerValue);
    
    //把数据保存到本地(注意:一定要保存,保存后才会写入磁盘)
    NSError *error=nil;
    BOOL ret=[self.context save:&error];
    if (!ret) {
        NSLog(@"insert data error %@",error.description);
    }
}

- (IBAction)deleteClick:(id)sender {
    NSArray *ary=[self fetchDataWithName:self.nameTF.text];
    for (UserModel *model in ary) {
        [self.context deleteObject:model];
    }
    NSError *error=nil;
    if (![self.context save:&error]) {
        NSLog(@"delete error %@",error.description);
    }
}

- (IBAction)updateClick:(id)sender {
    NSArray *ary=[self fetchDataWithName:self.nameTF.text];
    for (UserModel *model in ary) {
        model.age=@(self.ageTF.text.integerValue);
    }
    NSError *error=nil;
    if (![self.context save:&error]) {
        NSLog(@"update error %@",error.description);
    }
}

- (IBAction)fetchNameClick:(id)sender {
    NSArray *ary=[self fetchDataWithName:self.nameTF.text];
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:ary];
    [self.tableView reloadData];
}

- (IBAction)fetchAll:(id)sender {
    NSArray *ary=[self fetchDataWithName:nil];
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:ary];
    [self.tableView reloadData];
}

-(NSArray *)fetchDataWithName:(NSString *)name{
    //1、实例化一个查询请求
    NSFetchRequest *request=[[NSFetchRequest alloc] init];
    //2、设置要查询的数据模型
    request.entity=[NSEntityDescription entityForName:@"UserModel" inManagedObjectContext:self.context];
    //设置谓词,用于过滤数据,设置搜索条件
    if (name) {
        request.predicate=[NSPredicate predicateWithFormat:@"name like %@",name];
    }
    //排序
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    request.sortDescriptors=@[sort];
    return  [self.context executeFetchRequest:request error:nil];
}

#pragma mark - tableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    UserModel *model=self.dataArray[indexPath.row];
    cell.textLabel.text=[NSString stringWithFormat:@"name:%@,age:%@",model.name,model.age];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


0 0
原创粉丝点击