勾选 xcode的 CoreDate会帮我们自动创建 CoreData 但是我们通常不那样使用,通常把 CoreDate 在单例类中创建
//
// ZYDAO.h
// StoryboardTest
//
// Created by ninglihuan on 15/11/27.
// Copyright © 2015年 zzz. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "People.h"
@interface ZYDAO : NSObject
+ (instancetype)sharedDAO;
- (People* )insertPeopleWithName:(NSString* )name phone:(NSString* )phone;
- (NSArray* )selectAllPeople;
- (void)updatePeople;
- (void)deletePeople:(People* )people;
@end
//
// ZYDAO.m
// StoryboardTest
//
// Created by ninglihuan on 15/11/27.
// Copyright © 2015年 zzz. All rights reserved.
//
#import "ZYDAO.h"
@import CoreData;
NSString* const PEOPLE = @"People";
@interface ZYDAO () {
NSManagedObjectModel* _model;
NSPersistentStoreCoordinator* _coordinator;
NSManagedObjectContext* _context;
}
@end
@implementation ZYDAO
+ (instancetype)sharedDAO {
static ZYDAO* dao = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dao = [[ZYDAO alloc] init];
});
return dao;
}
- (id)init {
if (self = [super init]) {
NSURL* modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
_model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
_coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_model];
NSURL* sqliteURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"Model.sqlite"];
if (![_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqliteURL options:nil error:nil]) {
NSLog(@"打开数据库失败");
}
_context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_context setPersistentStoreCoordinator:_coordinator];
}
return self;
}
- (People* )insertPeopleWithName:(NSString* )name phone:(NSString* )phone {
People* people = [NSEntityDescription insertNewObjectForEntityForName:PEOPLE inManagedObjectContext:_context];
people.name = name;
people.phone = phone;
//把修改同步到数据库。
[_context save:nil];
return people;
}
- (NSArray* )selectAllPeople {
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:PEOPLE];
return [_context executeFetchRequest:request error:nil];
}
- (void)updatePeople {
[_context save:nil];
}
- (void)deletePeople:(People* )people {
[_context deleteObject:people];
[_context save:nil];
}
@end