MacOS CoreData(2)coredata DB连接/访问

ViewController.h文件 

// ViewController.h文件
#import <Cocoa/Cocoa.h>
#import <CoreData/CoreData.h>

#import "Person+CoreDataClass.h"
#import "Person+CoreDataProperties.h"

@interface ViewController : NSViewController

@end

ViewController.m文件 

// ViewController.m文件内容
#import "ViewController.h"

@interface ViewController(){
    NSManagedObjectContext *_context;
}
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _context = [self createDBContext];
    [self addPersonWithName:@"Jerry" sex:@"male" age:@100];
    [self addPersonWithName:@"Lily" sex:@"female" age:@20];
    [self addPersonWithName:@"Tom" sex:@"male" age:@80];
    
    [self modifyPersonWithName:@"Lily" sex:@"woman" age:@90];
    NSArray *allLily = [self getPersonByName:@"Lily"];
    NSLog(@"%lu",(unsigned long)allLily.count);
    for (Person *p in allLily) {
        NSLog(@"%@",p.name);
        NSLog(@"%@",p.sex);
        NSLog(@"%d",p.age);
    }
    
    [self removePerson:@"Lily"];
    // Do any additional setup after loading the view.
}

#pragma mark 1.创建管理上下文
- (NSManagedObjectContext *)createDBContext
{
    NSManagedObjectContext *context;
    //打开模型文件,参数为nil则打开包中所有模型文件并合并成一个

    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    //创建解析器NSPersistentStoreCoordinator

    NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
    //创建数据库保存路径(文件目录)
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@", path);
    ///path: Users/jerry.yang/Library/Containers/com.shztt.CoreDataDemo/Data/Documents
    path = [path stringByAppendingPathComponent:@"YC.db"];
    //添加SQLite持久存储到解析器
    NSError *error;
    [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:nil error:&error];
    if (error) {
        NSLog(@"数据库打开失败!错误: %@", error.localizedDescription);
    }
    else//数据库创建成功(打开成功)
    {
        context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
        context.persistentStoreCoordinator = storeCoordinator;
        NSLog(@"数据库打开成功!");
    }
    return context;
}


#pragma mark 2.插入数据
- (void)addPersonWithName:(NSString *)name sex:(NSString *)sex age:(NSNumber *)age
{
    //创建实体对象
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];
    person.name = name;
    person.sex = sex;
    person.age = age.intValue;
    //保存上下文
    NSError *error;
    [_context save:&error];
    if (error) {
        NSLog(@"添加过程中发送错误,错误: %@", error.localizedDescription);
    }
    else
    {
        NSLog(@"添加成功");
    }
}


#pragma mark 3.查询数据
//NSPredicate(谓词)是一个Foundation的类,它指定数据被获取或者过滤的方式。它的语言就像SQL的where和正则表达式的交叉一样。提供了具有表现力的,自然语言界面来定义一个集合。(被搜索的逻辑条件)
- (NSArray *)getPersonByName : (NSString *)name
{
    //创建一个请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    request.predicate = [NSPredicate predicateWithFormat:@"%K=%@",@"name", name];

    //上下文执行请求,得到查询结果
    NSArray *array = [_context executeFetchRequest:request error:nil];
    return array;
}

#pragma mark 4.删除数据
- (void)removePerson : (NSString *)name
{
    Person *person = [[self getPersonByName:name] firstObject];
    [_context deleteObject:person];
    NSError *error;
    [_context save:&error];
    if (error) {
        NSLog(@"删除过程中发生错误:%@", error.localizedDescription);
    }
    else
    {
        NSLog(@"删除成功");
    }
}


#pragma mark 修改数据
//必须首先提取出对应的实体对象,然后通过修改对象属性,最后保存
- (void)modifyPersonWithName : (NSString *)name sex : (NSString *)sex age : (NSNumber *)age{
    Person *person = [[self getPersonByName:name] firstObject];
    person.sex = sex;
    person.age = age.intValue;
    NSError *error;
    [_context save:&error];
    if (error) {
        NSLog(@"修改过程中发生错误: %@", error.localizedDescription);
    }
    else
    {
        NSLog(@"修改成功");
    }
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end

原理类比理解(不一定恰当):
1、通过名字的后缀xcdatamodeld可以观察到,这仅仅是一个数据模型,而不是存储的数据,真正的数据还是存储在DB中。SQLite数据库也是需要单独创建数据库文件
2、提供了一种机制或者是通道,在不用加载外部library的时候,直接访问db。而entity中为设计的DB字段值以及一些关联关系
3、资料介绍说,底层就相当于SQlite,所以coredata相当于一个SQLite访问连接库,只不过是一个具有苹果特色的数据库访问接口
4、与数据库类比理解:

  • xcdatamodeld:相当于数据库
  • Entity:相当于建立了一个数据表,
  • Entity中的Attributes:相当于设置数据表的字段值
  • DB数据库的数据需要存储在一个具体的db文件中,需指定路径
  • DB的访问接口 / 方式 -- 上下文
  • 创建上下文 == 创建具体的DB文件,并建立连接接口,此后对此数据表的的操作,都要用这个上下文统一接口来操作

    CoreDataDemo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

auspark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值