iOS Coredata的基本使用

2017-08-12 20:15:47来源:CSDN作者:hdg34jk人点击

分享

iOS Coredata的基本使用

  • coredata 管理类:NSManagedObjectModel、NSPersistentStoreCoordinator、NSManagedObjectContext。其中,NSManagedObjectModel是模型管理类,管理APP中的数据模型;NSPersistentStoreCoordinator将model和持久化存储联系起来,并且将上下文(NSManagedObjectContext)与持久化存储联系起来,其实就是充当解析器。NSManagedObjectContext是上下文类,负责管理数据的获取、创建和保存等工作。
  • coreda数据库创建

    (1)创建工程时,勾选“Use Core Data”选项
    这里写图片描述

    (2)在工程中选择新建文件,在新建文件界面选择新建“Data Model”, 点击next即可新建

-coredata创建数据模型
进入刚建好的数据库中,如下图点击“Add Entity”增加一个数据模型,双击该Entity进行重命名。点击2,在数据表中增加一个属性,双击该属性进行重命名,并且指定type类型。
这里写图片描述
点击“Style”,可以看到数据库中所有数据表的关系图。
这里写图片描述

注:iOS8之后,NSManagedObjectModel对NSManagedObject统一管理,不需要再次创建subClass,在使用时,直接引入#import “entity名称+CoreDataProperties.h”头文件即可。

-创建AppDataManager单例,管理数据表增删改查等基本操作。
(1)声明NSManagedObjectContext、NSManagedObjectModel、NSPersistentStoreCoordinator为实体变量,并实现初始化方法:

@interface AppDataManager() {    NSManagedObjectContext *objContext;    NSManagedObjectModel *objModel;    NSPersistentStoreCoordinator *persistentCoordinator;}@endstatic AppDataManager *sharedInstance = nil;@implementation AppDataManager+ (instancetype)sharedInstance {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        sharedInstance = [[AppDataManager alloc] init];    });    return sharedInstance;}- (instancetype)init {    self = [super init];    if (self) {        [self createObjModel];        [self createpersistentCoordinator];        [self createObjContext];    }    return self;}- (void)createObjModel {    if (!objModel) {        objModel = [NSManagedObjectModel mergedModelFromBundles:nil];    }}- (void)createpersistentCoordinator {    if (persistentCoordinator != nil) {        return;    }    persistentCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:objModel];    NSString *dir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;    NSString *path = [dir stringByAppendingString:@"CoredataDemo.db"];    NSURL *storeUrl = [NSURL fileURLWithPath:path];    NSError *error = nil;    [persistentCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error];    if (!error) {        NSLog(@"数据库打开成功");    } else {        NSLog(@"数据库打开失败:%@", [error description]);    }}- (void)createObjContext {    if (objContext != nil) {        return;    }    NSPersistentStoreCoordinator *coordinator = persistentCoordinator;    if (coordinator == nil) {        return;    }    objContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];    objContext.persistentStoreCoordinator = coordinator;}

(2)增加数据

- (BOOL)addScore:(NSDictionary *)dic {    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Score"];    request.predicate = [NSPredicate predicateWithFormat:@"identity=%@", dic[@"identity"]];    NSError *error = nil;    NSArray *results = [objContext executeFetchRequest:request error:&error];    if (error == nil) {        NSLog(@"score查询成功");    } else {        NSLog(@"score查询失败%@", [error description]);        return NO;    }    Score *score = nil;    if (results && results.count > 0) {        score = results.firstObject;    } else {        score = [NSEntityDescription insertNewObjectForEntityForName:@"Score" inManagedObjectContext:objContext];    }    score.name = dic[@"name"];    score.identity = dic[@"identity"];    score.score = dic[@"score"];    [objContext save:&error];    if (error == nil) {        NSLog(@"score 插入成功");        return YES;    } else {        NSLog(@"score插入失败%@", [error description]);        return NO;    }}

(3)删除数据

- (BOOL)deleteScore:(NSString *)identity {    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Score"];    request.predicate = [NSPredicate predicateWithFormat:@"identity=%@", identity];    NSError *error = nil;    NSArray *results = [objContext executeFetchRequest:request error:&error];    Score *score = nil;    if (error == nil) {        NSLog(@"查询score成功");    } else {        NSLog(@"查询score失败%@", [error description]);        return NO;    }    if (results && results.count) {        score = results.firstObject;    } else {        NSLog(@"数据中无符合条件的数据");    }    [objContext deleteObject:score];    [objContext save:&error];    if (error == nil) {        NSLog(@"score删除成功");        return YES;    } else {        NSLog(@"score删除失败%@", [error description]);        return NO;    }}

(4)修改数据

- (BOOL)updateScore:(NSDictionary *)dic {    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Score"];    request.predicate = [NSPredicate predicateWithFormat:@"identity=%@",dic[@"identity"]];    NSError *error = nil;    NSArray *results = [objContext executeFetchRequest:request error:&error];    if (error == nil) {        NSLog(@"score查询成功");    } else {        NSLog(@"score查询失败%@", [error description]);        return NO;    }    Score *score = nil;    if (results && results.count > 0) {        score = results.firstObject;    } else {        score = [NSEntityDescription insertNewObjectForEntityForName:@"Score" inManagedObjectContext:objContext];    }    score.identity = dic[@"identity"];    score.name = dic[@"name"];    score.score = dic[@"score"];    [objContext save:&error];    if (error == nil) {        NSLog(@"score更新成功");        return YES;    } else {        NSLog(@"score更新失败%@",[error description]);        return NO;    }}

(5)条件查询

- (NSArray *)getScore:(NSString *)identity {    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Score"];    request.predicate = [NSPredicate predicateWithFormat:@"identity=%@", identity];    NSError *error = nil;    NSArray *results = [objContext executeFetchRequest:request error:&error];    if (error == nil) {        NSLog(@"score查询成功");    } else {        NSLog(@"score查询失败:%@", [error description]);    }    return results;}

(6)获取全部数据

- (NSArray *)score {    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Score"];    NSError *error = nil;    NSArray *results = [objContext executeFetchRequest:request error:&error];    if (error == nil) {        NSLog(@"score查询成功");    } else {        NSLog(@"score查询失败:%@",[error description]);    }    return results;}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台