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