Core Data 数据持久化

Core Data

 

1.Core Data 是数据持久化存储的最佳方式 

2.数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型 

在Mac OS X 10.5Leopard及以后的版本中,开发者也可以通过继承NSPersistentStore类以创建自定义的存储格式 

3.好处:能够合理管理内存,避免使用sql的麻烦,高效 

4.构成:

创建工程时将core data选项勾选上, Xcode7之后会添加上include Unit Tests 选项, 可选可不选, 不选则系统默认将BOOL类型改为NSNumber类型

添加了 文件

在AppDelegate.h和AppDelegate.m中就会添加Core Data相应的属性和方法

AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
//被管理对象上下文
//内容, 在 coredata内 用来"临时"存储数据使用
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
//被管理对象模型
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
//持久化存储助理
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@end 

AppDelegate.m

(1)NSManagedObjectContext(被管理的数据上下文) 

操作实际内容(操作持久层)

作用:插入数据,查询数据,删除数据

(2)NSManagedObjectModel(被管理的数据模型) 

数据库所有表格或数据结构,包含各实体的定义信息 

作用:添加实体的属性,建立属性之间的关系

操作方法:视图编辑器,或代码

(3)NSPersistentStoreCoordinator(持久化存储助理) 

相当于数据库的连接器 

作用:设置数据存储的名字,位置,存储方式,和存储时

(4)NSManagedObject(被管理的数据记录) 

相当于数据库中的表格记录 

(5)NSFetchRequest(获取数据的请求) 

相当于查询语句 

(6)NSEntityDescription(实体结构) 

相当于表格结构

(7)后缀为.xcdatamodeld的包 

里面是.xcdatamodel文件,用数据模型编辑器编辑

编译后为.momd或.mom文件

打开文件,  点击左下角+号, 新建Person类

  

点击Editor 选择Create NSManagedObject Subclass创建数据模型, 自动生成Person Model

Core Data具体使用示例

在storyboad中创建删除 搜索 添加三个button 和 tableView

效果图:

具体实现代码:

#import "ViewController.h"
#import "AppDelegate.h"
#import "Person.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
- (IBAction)deletePerson:(id)sender;
- (IBAction)selectPerson:(id)sender;
- (IBAction)addPerson:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellID"];
    //初始化可变数组
    self.dataArr = [@[] mutableCopy];
    
    //从coredata本地取出存储的数据
    //1.找到app delegate
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    //2.创建检索对象
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    //通过检索上下文内取出相应地数组
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    //数组想要copy, 内部元素就必须遵守NSCoping协议
//    self.dataArr = [array mutableCopy];
    [self.dataArr addObjectsFromArray:array];
}

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

- (IBAction)deletePerson:(id)sender {
    //如果tableView处于编辑状态, 就取消编辑, 反之, 进入编辑状态
    if (self.tableView.editing) {
//        self.tableView.editing = NO;
        [self.tableView setEditing:NO animated:YES];
    } else {
         [self.tableView setEditing:YES animated:YES];
    }
}

- (IBAction)selectPerson:(id)sender {
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    //创建检索条件
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    request.predicate = [NSPredicate predicateWithFormat:@"age>25"];
    NSArray *selectArr = [app.managedObjectContext executeFetchRequest:request error:nil];
    //清空原先的数据
    [self.dataArr removeAllObjects];
    //将新的数据添加进数组中
    [self.dataArr addObjectsFromArray:selectArr];
    //刷新界面
    [self.tableView reloadData];
}

- (IBAction)addPerson:(id)sender {
    //使用coredata管理的对象, 需要继承自NSManagedObject
    //获取app delegate
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    //创建实体描述对象
    NSEntityDescription *description = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:app.managedObjectContext];
    //创建被管理对象
    //把被管理对象插入上下文内
    Person *p = [[Person alloc] initWithEntity:description insertIntoManagedObjectContext:app.managedObjectContext];
    NSArray *nameArr = @[@"闯神", @"龙神", @"宗主", @"班长", @"万少", @"四火", @"陈晨", @"金华", @"周洁", @"梦阳", @"欢欢", @"广恩", @"淑宁", @"艳萍"];
    p.name = nameArr[arc4random()%(nameArr.count)];
    //年龄随机[18, 27]
    p.age = @(arc4random()%10+18);
    //性别随机
    p.gender = @(arc4random()%2);
    //保存修改
    [app saveContext];
    //把person添加进tableView的数据源里面
    [self.dataArr addObject:p];
    [self.tableView reloadData];
}
#pragma mark-UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    Person *p = self.dataArr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"我叫%@, 年龄%@, 性别%@", p.name, p.age, [p.gender intValue] == 0?@"":@""];
    return cell;
}

#pragma mark-UITableViewDelegate
//提交tableView的编辑
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //1.
        AppDelegate *app = [[UIApplication sharedApplication] delegate];
        //2. 先找到这一行对应的model
        Person *p = self.dataArr[indexPath.row];
        //3. 从coredata的上下文内删除对应的对象
        [app.managedObjectContext deleteObject:p];
        //4. 从数组中删除对应的对象
        [self.dataArr removeObject:p];
        //5.从tableView中删除对应的cell
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];
    }
}
@end

 

原文地址:https://www.cnblogs.com/OrangesChen/p/5046569.html