概念介紹
coreData
NSManagedObjectContext 管理對(duì)象,上下文,持久性存儲(chǔ)模型對(duì)象憋沿,處理數(shù)據(jù)與應(yīng)用的交互,托管對(duì)象上下文谨朝,數(shù)據(jù)庫的大多數(shù)操作是在這個(gè)類操作
NSManagedObjectModel 被管理的數(shù)據(jù)模型卤妒,數(shù)據(jù)結(jié)構(gòu)甥绿,托管對(duì)象模型字币,其中一個(gè)托管對(duì)象模型關(guān)聯(lián)到一個(gè)模型文件,里面存儲(chǔ)著數(shù)據(jù)庫的數(shù)據(jù)結(jié)構(gòu)共缕。
NSPersistentStoreCoordinator 添加數(shù)據(jù)庫洗出,設(shè)置數(shù)據(jù)存儲(chǔ)的名字,位置图谷,存儲(chǔ)方式翩活,持久化存儲(chǔ)協(xié)調(diào)器,主要負(fù)責(zé)協(xié)調(diào)上下文存儲(chǔ)的區(qū)域的關(guān)系便贵。
NSManagedObject 被管理的數(shù)據(jù)記錄菠镇,托管對(duì)象類,其中CoreData里面的托管對(duì)象都會(huì)繼承此類承璃。
NSFetchRequest 數(shù)據(jù)請(qǐng)求
NSEntityDescription 表格實(shí)體結(jié)構(gòu)
NSPredicate 過濾條件利耍,找到要修改的對(duì)象
model文件參考
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface User : NSManagedObject
//屬性的類型一旦創(chuàng)建不可修改,如需修改,必須刪除APP中舊的數(shù)據(jù)庫文件隘梨,否則崩潰
@property (nonatomic,strong) NSString* name;
@property (nonatomic,assign) BOOL sex;
@property (nonatomic,strong)UIImageView* image;
@property (nonatomic,strong) NSString* aID;
@property (nonatomic,assign) float height;//和CoreDataProject.xcdatamodeld中的UserEntity中的類型一致程癌,不可以是CGFloat
@property (nonatomic,assign) NSInteger age;
@end
NS_ASSUME_NONNULL_END
ViewController文件參考
//
// ViewController.m
// CoreDataProject
//
// Created by alex black on 2019/3/20.
// Copyright ? 2019 JTB.com. All rights reserved.
//
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "User.h"
@interface ViewController ()
@property (nonatomic,strong) NSManagedObjectContext *context;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
//CoreDataProject.xcdatamodeld文件 編譯后就是 CoreDataProject.momd 所以名字要對(duì)應(yīng)
NSURL *modelPath = [[NSBundle mainBundle] URLForResource:@"CoreDataProject" withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelPath];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
dataPath = [dataPath stringByAppendingFormat:@"/People.sqlite"];//自己定義的數(shù)據(jù)庫名字 千萬別忘記加/ 否則真機(jī)無法創(chuàng)建相應(yīng)文件
[coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:nil];
context.persistentStoreCoordinator = coordinator;
self.context = context;
}
#pragma mark - 插入操作
- (void)insertMethod:(NSManagedObjectContext*)context
{
//@"UserEntity" 要和 CoreDataProject.xcdatamodeld文件中定義的model名字一樣 特別注意:User中的屬性描述必須和UserEntity的屬性描述一致,否則無法存入轴猎,例如User的height是CGFloat 而 UserEntity的height是Float嵌莉,類型不一致無法存入信息,也無法修改
User* obj = (User*)[NSEntityDescription insertNewObjectForEntityForName:@"UserEntity" inManagedObjectContext:context];
obj.name = @"ee";
obj.sex = YES;
obj.age = 18;
obj.height = 180;
User* obj2 = (User*)[NSEntityDescription insertNewObjectForEntityForName:@"UserEntity" inManagedObjectContext:context];
obj2.name = @"pp";
obj2.sex = NO;
obj2.age = 16;
obj2.height = 160;
NSError *error1;
if (context.hasChanges) {
[context save:&error1];
}
if (error1) {
NSLog(@"error1 = %@",error1);
}
}
#pragma mark - 刪除操作
- (void)deleteMethod:(NSManagedObjectContext*)context{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"UserEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"ee"];
request.predicate = predicate;
NSError *error2;
NSArray<User*> *deleteArr = [context executeFetchRequest:request error:&error2];
[deleteArr enumerateObjectsUsingBlock:^(User * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[context deleteObject:(NSManagedObject*)obj];
}];
if ([context hasChanges]) {
[context save:nil];
}
if (error2) {
NSLog(@"%@",error2);
}
}
#pragma mark - 修改操作
- (void)changeMethod:(NSManagedObjectContext*)context{
NSFetchRequest *request1 = [NSFetchRequest fetchRequestWithEntityName:@"UserEntity"];
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name=%@",@"pp"];
request1.predicate = predicate1;
NSError *error3 = nil;
NSArray<User*> *chageArr = [context executeFetchRequest:request1 error:&error3];
[chageArr enumerateObjectsUsingBlock:^(User * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj.height = 133;
}];
if ([context hasChanges]) {
[context save:nil];
}
if (error3) {
NSLog(@"%@",error3);
}
}
#pragma mark - 查找操作
- (void)queryMethod:(NSManagedObjectContext*)context{
NSFetchRequest *request4 = [NSFetchRequest fetchRequestWithEntityName:@"UserEntity"];
NSError *error4 = nil;
NSArray<User *> *quertArr = [context executeFetchRequest:request4 error:&error4];
[quertArr enumerateObjectsUsingBlock:^(User * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"User Name : %@, Height : %@, age : %d", obj.name, @(obj.height), obj.age);
}];
// 錯(cuò)誤處理
if (error4) {
NSLog(@"%@", error4);
}
}
- (IBAction)buttonClick:(UIButton *)sender {
if (sender.tag == 1) {
[self insertMethod:self.context];
}else if (sender.tag == 2) {
[self deleteMethod:self.context];
}else if (sender.tag == 3) {
[self changeMethod:self.context];
}else if (sender.tag == 4) {
[self queryMethod:self.context];
}
}
@end