美文网首页
3.8 NSManagedObjectContext 数据库管理

3.8 NSManagedObjectContext 数据库管理

作者: 草根小强 | 来源:发表于2019-04-22 11:03 被阅读0次

    NSManagedObjectContext 数据库管理上下文

    #import "ViewController.h"
    
    #import <CoreData/CoreData.h>
    #import "Person+CoreDataProperties.h"
    #import "PetsViewController.h"
    
    @interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
    
    // 数据库管理上下文
    @property (nonatomic, strong) NSManagedObjectContext *context;
    
    // 数据源数组
    @property (nonatomic, strong) NSMutableArray *dataSource;
    // 界面展示
    @property (nonatomic, strong) UITableView *tableView;
    
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        // 导航栏元素
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAction)];
        
        // 准备数据库
        [self prepareForCoreData];
        
        
        // 实例化tableView
        [self initTableView];
    }
    
    - (void)initTableView {
        self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        
        [self.view addSubview:self.tableView];
    }
    
    /** 导航栏右上角元素点击事件 */
    - (void)addAction {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入用户的信息" preferredStyle:UIAlertControllerStyleAlert];
        
        // 用户名字输入框
        [alert addTextFieldWithConfigurationHandler:^(UITextField *  textField) {
            
            textField.placeholder = @"请输入用户名称";
            textField.font = [UIFont systemFontOfSize:13];
        }];
        
        // 身份证输入框
        [alert addTextFieldWithConfigurationHandler:^(UITextField *  textField) {
           
            textField.placeholder = @"请输入身份证号码";
            textField.font = [UIFont systemFontOfSize:13];
        }];
        
        // 取消按钮
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        // 保存按钮
        UIAlertAction *actionDone = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
            
            // 触发增操作
            [self saveAction:alert];
        }];
        
        
        [alert addAction:actionCancel];
        [alert addAction:actionDone];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    // 弹窗保存按钮事件
    - (void)saveAction:(UIAlertController *)alert {
        
        // 1. 获取两个输入框里面的内容
        UITextField *usernameText = alert.textFields.firstObject;
        UITextField *personIDText = alert.textFields.lastObject;
        
        NSString *username = usernameText.text;
        NSNumber *personID = @(personIDText.text.integerValue);
        
        // 2. person模型
        Person *p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
        
        p.name = username;
        p.personID = personID;
        
        // 3. 保存到本地
        [self.context save:nil];
        
        // 4. 界面展示
        [self.dataSource addObject:p];
        [self.tableView reloadData];
    }
    
    
    #pragma mark ------ 协议 -------
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        
        return self.dataSource.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        
        static NSString *reuseid = @"cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseid];
        
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseid];
        }
        
        // 展示
        Person *p = self.dataSource[indexPath.row];
        
        cell.textLabel.text = p.name;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", p.personID];
        
        
        
        return cell;
        
    }
    
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        // 获取这一行显示的数据
        Person *p = self.dataSource[indexPath.row];
        
        // 1. 从界面显示删除
        [self.dataSource removeObject:p];
        [self.tableView reloadData];
        
        // 2. 从本地缓存中删除
        [self.context deleteObject:p];
        [self.context save:nil];
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        
        PetsViewController *vc = [[PetsViewController alloc] init];
        
        // 获取到当前要显示的person的模型, 并传给下一个界面
        vc.p = self.dataSource[indexPath.row];
        // 把这个界面实例化好的数据库管理上下文, 传给下个界面使用
        vc.context = self.context;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    #pragma mark ------ 数据库操作 -----
    - (void)prepareForCoreData {
        
        // 1. 实例化管理上下文
        self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        
        // 获取路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"CoreDataDemo" ofType:@"momd"];
        
        // 实例化数据管理模型
        NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
        
        // 实例化协调器
        NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 设置数据库文件保存的路径
        // ~/
        NSString *storePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"/person.db"];
        
        // 设置存储类型
        [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:storePath] options:nil error:nil];
        
        // 2. 设置数据存储的协调器
    //    self.context.persistentStoreCoordinator = coordinator;
        [self.context setPersistentStoreCoordinator:coordinator];
    }
    
    // 查询所有数据
    - (NSArray *)findAll {
        
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
        
        return [self.context executeFetchRequest:request error:nil];
    }
    
    
    
    
    
    #pragma mark ------ 懒加载实现 --------
    - (NSMutableArray *)dataSource {
        if (_dataSource == nil) {
            _dataSource = [[NSMutableArray alloc] init];
            // 读取本地缓存的数据, 并默认填充到数据源数组中
            [_dataSource addObjectsFromArray:[self findAll]];
        }
        
        return _dataSource;
    }
    @end
    

    Person+CoreDataProperties类

    #import "Person.h"
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Person (CoreDataProperties)
    
    @property (nullable, nonatomic, retain) NSString *name;
    @property (nullable, nonatomic, retain) NSNumber *personID;
    @property (nullable, nonatomic, retain) NSSet *pets;
    
    @end
    
    @interface Person (CoreDataGeneratedAccessors)
    
    - (void)addPetsObject:(NSManagedObject *)value;
    - (void)removePetsObject:(NSManagedObject *)value;
    - (void)addPets:(NSSet *)values;
    - (void)removePets:(NSSet *)values;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Person+CoreDataProperties.h"
    
    @implementation Person (CoreDataProperties)
    
    @dynamic name;
    @dynamic personID;
    @dynamic pets;
    
    @end
    

    Person类

    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Person : NSManagedObject
    
    // Insert code here to declare functionality of your managed object subclass
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Person+CoreDataProperties.h"
    
    #import "Person.h"
    
    @implementation Person
    
    // Insert code here to add functionality to your managed object subclass
    
    @end
    

    Dog+CoreDataProperties类

    #import "Dog.h"
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Dog (CoreDataProperties)
    
    @property (nullable, nonatomic, retain) NSString *name;
    @property (nullable, nonatomic, retain) NSString *kind;
    @property (nullable, nonatomic, retain) Person *master;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Dog+CoreDataProperties.h"
    
    @implementation Dog (CoreDataProperties)
    
    @dynamic name;
    @dynamic kind;
    @dynamic master;
    
    @end
    

    Dog类

    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
    
    @class Person;
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Dog : NSManagedObject
    
    // Insert code here to declare functionality of your managed object subclass
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Dog+CoreDataProperties.h"
    
    #import "Dog.h"
    #import "Person.h"
    
    @implementation Dog
    
    // Insert code here to add functionality to your managed object subclass
    
    @end
    
    coreData1.png
    coreData2.png
    coreData3.png
    数据库管理上下文1.png
    数据库管理上下文2.png

    相关文章

      网友评论

          本文标题:3.8 NSManagedObjectContext 数据库管理

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