----欢迎-------
在移动端开发,数据持久化保存是基本要素,没钱在2014年之后退出了coredate,本持久化基于oc作为开发,方便程序人员操作。与SQL数据库,MySQL相比,优点颇多。
1.首先,coredate不需要开发人员去操作数据复杂的一些语句,摆脱sql语句种种限制条件;
2.coredate使用,减少了开发人员对数据的管理,有NSManagedObjectContext托管上下文帮助开发人员去管理数据,当我们获取数据时由NSFetchedResultsController去代替程序人员捕做数据;
3.减少开发人员在项目工程里面对颇多数据库操作复杂语言,减少项目的内存在泄漏。2014年7月出xcode6测试版本后,coredate又进一步更新,稳定性更高。当然在项目中到底归结使用哪种数据持久化保存,还是看项目的架构,有公司制定。
下面我们看下coredate的使用方法;
当你使用coredate时,在APPdelegate.h文件里
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;//Context上下文意思,
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;//这个程序员不掉用,而是coredata自己用的,将数据转sql命令
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;//协调器,也不是我们调用的,
- (void)saveContext;//这个方法也不需要我们管
- (NSURL *)applicationDocumentsDirectory;//要管理目录的,也需要在沙盒里写入sql的文件,也不需要我们管理
在APPdelegate.m文件里
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.shangguan.guoqing.coredata__1_" in the application‘s documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"coredata__1_" withExtension:@"momd"];
//withExtension后面是扩展文件,是个工程目录的文件名字匹配的
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"coredata__1_.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application‘s saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application‘s saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
这是coredate生成的基本文件以及方法,不可盲目修改和删除。其中
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"coredata__1_" withExtension:@"momd"];
withExtension后面是扩展文件,是个工程目录的文件名字匹配的
下面我们看下coredate保存数据
//先获取上下文对象
NSLog(@"%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]);
//UIApplication是程序运行你这个程序的时候都会给实力化一个UIApplication对象出来,UIApplication对象就代表你当前的程序,并且是唯一
可以这样去获取appdelegate里面的对象
AppDelegate * app = [UIApplication sharedApplication].delegate;
NSManagedObjectContext * context = app.managedObjectContext;//将来负责管理数据的玩意,上下文
//所有实体类都继承与一个类,就是NSManagedObject,叫托管对象。这个时候我们需要实例化一个对象,但是不能直接实例化,需要托管对象建立连接,可以认为通过上下文建立一个空白的托管对象
/*1种方法
//这里需要借助NSEntityDescription实体描述类,相当于描述这个实体里面有什么东西。
NSManagedObject * manager = [NSEntityDescription insertNewObjectForEntityForName:@"Gooder" inManagedObjectContext:context];
//下面我门就要处理数据了,因为没有具体对应press类,所以对象都是父类子类的实例,自己扩展出来的属性无法使用点语法。manager是所有实体的父类,但是没有直接拿出来manager.age等属性,所以我们利用kvc来赋值
[manager setValue:self.textname.text forKey:@"name"];
[manager setValue:@(self.textage.text.intValue) forKey:@"age"];//其中@()代表把当前integer转化为nsnumber类型的
[manager setValue:self.textress.text forKey:@"addres"];
//保存上下文,此时NSManagedObject还没有保存到数据库里面呢,这个时候的对象状态叫瞬时态,啪,一断电就没了,就是没有保存上。我们要持久状态,就是保存
//此时咱们只需要调用一个方法,就会自动监测上下文有没有瞬时态对像,如果有就自动保存上,写进数据库里面
NSError * error = nil;
[context save:&error];
if (error == nil) {
NSLog(@"保存成功");
}else
{
NSLog(@"保存错误");
}
*/
//2.种方法
Gooder * gooder = [NSEntityDescription insertNewObjectForEntityForName:@"Gooder" inManagedObjectContext:context];
gooder.name = self.textname.text;
gooder.age = @(self.textage.text.intValue);
gooder.addres = self.textress.text;
NSError * error = nil;
[context save:&error];
if (error == nil) {
NSLog(@"保存成功");
[self.navigationController popViewControllerAnimated:YES];
}else
{
NSLog(@"保存错误");
}