CoreData
参考了前辈的作品:http://blog.csdn.net/kesalin/article/details/6739319
1.ManagedObjectModel :
描述应用程序的数据模型 包含了实体(Entity) 属性(Property) 读取数据的等
1 //xcdataModeld文件编译后为momd文件 从资源文件中加载NSManagedObjectModel对象
2 NSURL *url = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
3 _model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
2.ManagedObjectContext:
ManagedObjectContext 参与对数据操作的全过程 并检测数据对象的变化 下面的代码可看出到处都有 他的影子
//通过NSManagedObjectModel对象创建NSPersistentStoreCoordinator对象
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_model];
////数据库的增\删\改\查
//插入
- (void)insertWithName:(NSString *)name
{
People *people = [NSEntityDescription insertNewObjectForEntityForName:ENTITY_NAME inManagedObjectContext:_context];
people.name = name;
//baocunxiugai
NSError *error = nil;
if (![_context save:&error])
{
NSLog(@"插入数据失败");
}
}
//检索所有
- (NSArray *)searchAll
{
NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:ENTITY_NAME];
NSArray *resultArr = [_context executeFetchRequest:req error:nil];
return resultArr;
}
//更新对象
- (void)updateWithPeople:(People *)people
{
NSError *error = nil;
if (![_context save:&error])
{
NSLog(@"Update fail");
}
}
//删除数据
- (void)deletePeople:(People *)people
{
[_context deleteObject:people];
NSError *error = nil;
if (![_context save:&error])
{
NSLog(@"Delete fail");
}
}
3.PersistentStoreCoordinator:
PersistentStoreCoordinator相当于数据文件管理器 处理底层对数据文件的读取与写入
//文件夹路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Model.sqlite"];
//加载文件
if ([_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:nil error:nil])
{
_context = [[NSManagedObjectContext alloc] init];
//为NSManagedObjectContext对象设置存储协调者
[_context setPersistentStoreCoordinator:_persistentStoreCoordinator];
}
else
{//加载出错 就崩溃
abort();
}
4.ManagedObject
数据对象 与ManagedObjectContext相关联