关于Core Data的一些整理(一)

在Xcode7.2中只有Mast-Debug和Single View中可以勾选Use Core Data

如果勾选了Use Core Data,Xcode会自动在AppDelegate中帮你生成Core Data的核心代码,并且自动生成.xcdatamodeld数据文件
 
 //Appdelegate.h中
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext;
- (NSURL *)applicationDocumentsDirectory; @end //Appdelegate.m中系统帮助生成的代码
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
} #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 "qq100858433.JMHitList" 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:@"JMHitList" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
} - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns 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:@"JMHitList.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: 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] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_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();
}
}
} @end

假如你在.xcdatamodeld中生成了如下实体和实体属性:

那么在VC中获取数据库内容和添加数据库内容的代码如下:
   //从Core Data中获得已有数据
id appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
@try {
self.people = [NSMutableArray arrayWithArray:[managedContext executeFetchRequest:fetchRequest error:nil]];
}
@catch (NSException *exception) {
NSLog(@"Could not fetch %@", [exception userInfo]);
}
@finally {
NSLog(@"Fetch Successful");
} //为数据库添加实体实例
id appDelegate = [UIApplication sharedApplication].delegate;
//NSManagedObjectContext可以看做内存中用来处理managedObjects的暂存器
NSManagedObjectContext *mangedContext = [appDelegate managedObjectContext];
//下面两种方法都可以获得Person实体
// NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:mangedContext];
// NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:mangedContext];
// [person setValue:name forKey:@"name"];
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:mangedContext];
[person setValue:name forKey:@"name"];
@try {
[mangedContext save:nil];
[self.people addObject:person];
}
@catch (NSException *exception) {
NSLog(@"Could not save %@", [exception userInfo]);
}
@finally {
NSLog(@"Save Successfullt!");
}
 
 
 

关于Core Data的一些整理(一)的更多相关文章

  1. 关于Core Data的一些整理(五)

    关于Core Data的一些整理(五) 在Core Data中使用NSFetchedResultsController(以下简称VC)实现与TableView的交互,在实际中,使用VC有很多优点,其中 ...

  2. 关于Core Data的一些整理(四)

    关于Core Data的一些整理(四) 调用Core Data文件中的Request模板进行条件匹配 //获取ObjectModel相当于获取Core Date文件 NSManagedObjectMo ...

  3. 关于Core Data的一些整理(三)

    关于Core Data的一些整理(三) 关于Core Data Stack的四种类与它们的关系如下: NSManagedObjectModel NSPersistentStore NSPersiste ...

  4. 关于Core Data的一些整理(二)

    关于Core Data的一些整理(二) 创建NSManagedObject的子类时,有一点是在这中间要强调的一点是,要不要勾选 Use scalar properties for primitive ...

  5. Core Data 学习简单整理01

    Core Data是苹果针对Mac和iOS平台开发的一个框架, 通过CoreData可以在本地生成数据库sqlite,提供了ORM的功能,将对象和数据模型相互转换 . 通过Core Data管理和操作 ...

  6. 《驾驭Core Data》 第三章 数据建模

    本文由海水的味道编译整理,请勿转载,请勿用于商业用途.    当前版本号:0.1.2 第三章数据建模 Core Data栈配置好之后,接下来的工作就是设计对象图,在Core Data框架中,对象图被表 ...

  7. 《驾驭Core Data》 第二章 Core Data入门

    本文由海水的味道编译整理,请勿转载,请勿用于商业用途.    当前版本号:0.4.0 第二章 Core Data入门 本章将讲解Core Data框架中涉及的基本概念,以及一个简单的Core Data ...

  8. 《驾驭Core Data》 第一章 Core Data概述

    <驾驭Core Data>系列教程综合了<Core Data for iOS>,<Learning Core Data for iOS>,<Core Data ...

  9. iOS之Core Data及其线程安全

    一.简介 Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对 ...

随机推荐

  1. ios入门之c语言篇——基本函数——4——数值交换函数

    一个常用函数,被整理出来,免得每次 都要写 参数返回值解析: 参数: *a:int*,需要交换值的第一个变量: *b:int*,需要交换值的第二个变量: 返回值: (无) 函数解析: swap(&am ...

  2. CreateProcessWithLogonW(好像可以指定进程的上下文环境)

    Creates a new process and its primary thread. Then the new process runs the specified executable fil ...

  3. 转:Lua简明教程

    需要注意的是:lua中的变量如果没有特殊说明,全是全局变量,那怕是语句块或是函数里. 这里很奇怪,为什么在函数内部声明的变量默认也是global的呢? 函数的返回值 和Go语言一样,可以一条语句上赋多 ...

  4. 疯狂java讲义笔记 2.3.7

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&q ...

  5. VS2012(update3)编译Qt5.1.1 32位静态库debug-and-release版及结果分享

    1. 下载zip源码,我下载的是qt-everywhere-opensource-src-5.1.1.zip这个文件. 2.安装python 3.解压缩qt-everywhere-opensource ...

  6. Apache CXF多个远程拒绝服务漏洞(CVE-2013-2160)

    漏洞版本: Apache Group CXF <= 2.5.10 Apache Group CXF 2.7.4 Apache Group CXF 2.6.7 漏洞描述: BUGTRAQ ID: ...

  7. Qt入门(12)——Qt国际化

    应用的国际化就是使应用成为能被非本国的人使用的过程.有的情况下,国际化很简单,例如,使一个US应用可被Australian或者British用户理解,工作可能少于几个拼写修正.但是使一个US应用可以被 ...

  8. 动态规划:NOI 2009 管道取珠

    [NOI2009] 管道取珠 输入文件:ballb.in   输出文件:ballb.out   简单对比 时间限制:1 s   内存限制:512 MB #include <iostream> ...

  9. socket(TCP)发送文件

    一:由于在上一个随笔的基础之上拓展的所以直接上代码,客户端: using System; using System.Collections.Generic; using System.Componen ...

  10. HDU4099 Revenge of Fibonacci(高精度+Trie)

    Revenge of Fibonacci Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 204800/204800 K (Java/ ...