创建项目的时候没有选CoreData ,写到一半想加进去怎么办?
其实很简单,@import CoreData;
@interface ForModel (){
NSManagedObjectModel _model;
NSPersistentStoreCoordinator_coordinator;
NSManagedObjectContext*_context;
}
@end
@implementation Fengzhuang
+(instancetype)sharedDao{
static ForModel*dao=nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dao=[[ForModel alloc]init];
});
return dao;
}
-(id)init{
if (self=[super init]) {
NSURL *momdURL=[[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
_model=[[NSManagedObjectModel alloc]initWithContentsOfURL:momdURL];
_coordinator =[[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:_model];
NSURL *SQLiteURL=[[[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject] URLByAppendingPathComponent:@"Test.sqlite"];
if ([_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:SQLiteURL options:nil error:nil]) {
_context=[[NSManagedObjectContext alloc]init];
[_context setPersistentStoreCoordinator:_coordinator];
}
else
{
exit(0);
}
}
return self;
}
-(People*)insertPeopleWithName:(NSString *)name phone:(NSString )phone header:(UIImage )header
{
Peoplepeople=[NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:_context];
people.name=name;
people.phone=phone;
people.img=header;
[_context save:nil];
return people;
}
-(NSArray)selectedAll
{
NSFetchRequest *reuest=[[NSFetchRequest alloc]initWithEntityName:@"People"];
return [_context executeFetchRequest:reuest error:nil];
}
-(void)updatePeople:(People *)people
{
[_context save:nil];
}
-(void)deletePeople:(People *)people
{
[_context deleteObject:people];
[_context save:nil];
}
想用这个方法要先创建一个MOdel类如下:
iOS <wbr>如何中途创建 <wbr>Core <wbr>Data数据库?
iOS <wbr>如何中途创建 <wbr>Core <wbr>Data数据库?
然后创建一个属于它本身的单例类
iOS <wbr>如何中途创建 <wbr>Core <wbr>Data数据库?
一直点next就行了,创建完成是这样的:
iOS <wbr>如何中途创建 <wbr>Core <wbr>Data数据库?