iOS-Core Data基础
Core Data基础
Core Data是一个API集合,被设计用来简化数据对象的持久存储。
在此先不普及概念,先通过一个简单的案例使用来感受一下Core Data的精妙之处。
在创建工程的时候勾选Use Core Data.

创建好项目,我们可以看到在左侧任务栏多了一个CoreDataDemo.xcdatamodeld。暂且先不管这个文件。

此时如果我们打开AppDelegate.h和AppDelegate.m文件,会发现比平时多了很多的内容。
下面是生成的声明文件和实现文件。
#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.h
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (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 "com.wyg.CoreDataDemo" 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:@"CoreDataDemo" withExtension:@"momd"];
_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:@"CoreDataDemo.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] 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();
}
}
}
@end
AppDelegate.m
可能初次接触感觉密密麻麻的,那我们暂且也不用管它,既然系统为我们自动生成,我们直接使用就行了。
现在我们点击进去CoreDataDemo.xcdatamodeld这个文件,我们可以看到下面的界面。

Add Entity(添加实体) Add Attribute(添加属性) Editor Style(编辑风格)
现在我们添加一个Entity,命名为People,添加属性name,age
现在我们再添加一个Entity,命名位Book,添加属性name,author

现在我们可以添加People和Book的关系。
在上图中我们可以看到Relationships这个词(显示的是People,Book这一同理)。
我们想要在People中添加一个Book,表名Book是People的一个属性,可以简单理解为人有书
在Book中添加一个People,表名People是Book的一个属性,可以简单理解为书有主人

此时选择Editor Style,我们可以看到下图:

我们使用界面图形工具创建了一个People,一个Book,我们如何让他们生成实际的类呢?
选择菜单栏中的 Editor->create NSManagedObject subclass(也可以在command+n->Core Data->NSManagedObject subclass)


执行完上述步骤系统会为我们生成People,Book类。

下面是Book和People类文件,其中People类中我们发现NSManagedObject修饰book,我们将其修改位Book就行,并写上@class Book;有时会出现这个小问题。
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> @class People; @interface Book : NSManagedObject @property (nonatomic, retain) NSNumber * name;
@property (nonatomic, retain) NSString * author;
@property (nonatomic, retain) People *people; @end
Book.h
#import "Book.h"
#import "People.h" @implementation Book @dynamic name;
@dynamic author;
@dynamic people; @end
Book.m
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> @interface People : NSManagedObject @property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSManagedObject *book; @end
People.h
#import "People.h" @implementation People @dynamic name;
@dynamic age;
@dynamic book; @end
People.m
到现在为止,万事俱备,只欠代码了。
我们对Core Data的操作,无外乎增删改查,直接上代码
在AppDelegate启动函数中,添加以下代码是往Core Data中添加一条记录:
//托管对象上下文,有点类似于数据库
NSManagedObjectContext *context = self.managedObjectContext;
//实例,有点类似于表,插入一条数据,并给对象属性赋值
People *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context];
people.name = @"wyg"; Book *book =[NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context];
book.name = @"三国演义"; people.book = book; [self saveContext];
增
NSManagedObjectContext *context = self.managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"People" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
request.entity = entity;
NSArray *arr = [context executeFetchRequest:request error:nil]; for (People *object in arr)
{
NSLog(@"%@,%@",object.name,object.book.name);
}
查
查得结果:

关于修改和删除,跟上面原理差不多,首先是查找结果集,假设要删除某条数据,可以使用:[context deleteObject:object];
对某条数据修改,可以直接使用:[object setValue:@"小明" forKey:@"name"];//将姓名修改为小明。
1.Key 0x889f2f0(:Key:0x889e400<-://981A476D-55AC-4CB4-BBD8-E0285E522412/Key/p1489> ; data: <fault>)
出现的可能原因:当时我创建的时候,勾选了core data,它会在delegate.m文件中生成一些操作,但是如果你在其它控制器中想要操作的话,就要获取core data的相关对象,我的当时的做法是:
app = [AppDelegate new];
NSManagedObjectContext *context = app.managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteModel" inManagedObjectContext:context];
NSFetchRequest *request = [NSFetchRequest new];
request.entity = entity;
[request setReturnsObjectsAsFaults:NO];
notes = [context executeFetchRequest:request error:nil];
[collection reloadData];
code
如果我将app设置位局部变量,就会出现上述错误,我的解决办法是将其设置为全局变量。具体原因可以参考:http://imtx.me/archives/1888.html
iOS-Core Data基础的更多相关文章
- Core Data系列文章(一)Core Data基础
在iOS开发数据库SQLite的使用介绍了iOS中使用SQLite对数据进行持久化存储,实际上是对数据库直接进行操作,而苹果专门有一套API来间接的对数据进行持久化存储,而且主要针对用户创建的对象 - ...
- iOS:Core Data 中的简单ORM
我们首先在xcdatamodel文件中设计我们的数据库:例如我建立一个Data的实体,里面有一个String类型的属性name以及一个Integer类型的num: 然后选中Data,添加文件,选择NS ...
- iOS Core data多线程并发访问的问题
大家都知道Core data本身并不是一个并发安全的架构:不过针对多线程访问带来的问题,Apple给出了很多指导:同时很多第三方的开发者也贡献了很多解决方法.不过最近碰到的一个问题很奇怪,觉得有一定的 ...
- iOS: Core Data入门
Core Data是ORM框架,很像.NET框架中的EntityFramework.使用的基本步骤是: 在项目属性里引入CoreData.framework (标准库) 在项目中新建DataModel ...
- IOS - CORE DATA的目录(xcode6)
当使用coredata作为app的后台数据存储介质后,我们很想知道数据是否成功插入.为此,我想找到coredata.sqlite的文件 代码中指定的存储目录为: - (NSURL *)appli ...
- iOS Core Data 数据库的加密(待研究)
https://github.com/project-imas/encrypted-core-data 使用起来很方便,底层还是使用了SQLCipher,有时间要研究一下! 数据库的密码不能用固定字符 ...
- 《驾驭Core Data》 第三章 数据建模
本文由海水的味道编译整理,请勿转载,请勿用于商业用途. 当前版本号:0.1.2 第三章数据建模 Core Data栈配置好之后,接下来的工作就是设计对象图,在Core Data框架中,对象图被表 ...
- iOS教程:Core Data数据持久性存储基础教程
目录[-] 创建Core Data工程 创建数据模型 测试我们的数据模型 来看看SQL语句的真面目 自动生成的模型文件 创建一个表视图 之后看些什么? 就像我一直说的,Core Data是iOS编程, ...
- iOS 数据持久化(3):Core Data
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css); @import url(/ ...
随机推荐
- 在DataGridView控件中显示图片
实现效果: 知识运用: DataGridView控件的DataSource属性 实现代码: private void Form1_Load(object sender, EventArgs e) { ...
- Dojo的dojoConfig函数
在我们引入 Dojo 的时候都会先做一些全局的配置,所使用的就是 Dojo 的 Config 接口. dojoConfig为以前的dgConfig函数. <script type="t ...
- 点击按钮在表格的某一行下,在添加一行(HTML+JS)
使用js在指定的tr下添加一个新的一行newTr html代码: <table> <tr> <td>用户名:</td> <td><in ...
- 使用vs2013打开VS2015的工程文件的解决方案(适用于大多数vs低版本打开高版本)
前言:重装系统前我使用的是vs2015(有点装*),由于使用2015实在在班上太另类了, 导致我想在其他同学的vs下看一看我写的代码都无法达成! 而且最关键的是交作业的时候,老师的2013也没有办法打 ...
- 使用lua做序列化和反序列化
-- lua对象序列化 function serialize(obj) local lua = "" local t = type(obj) if t == "numbe ...
- java 会话跟踪技术
1.session用来表示用户会话,session对象在服务端维护,一般tomcat设定session生命周期为30分钟,超时将失效,也可以主动设置无效: 2.cookie存放在客户端,可以分为内存c ...
- 【思维题 费用流 技巧】bzoj5403: marshland
主要还是网络流拆点建图一类技巧吧 Description JudgeOnline/upload/201806/1(4).pdf 题目分析 第一眼看到这题时候只会把每个点拆成4个方向:再强制定向连边防止 ...
- Docker DockerFile文件指令 & 构建
1.dockerfile指令格式 # Comment注释 INSTRUCTION argument指令名 + 参数 2.普通指令 1. FROM 已存在的镜像,基础镜像,第一条非注释指令 FROM & ...
- Docker 镜像&仓库 获取及推送镜像
docker查看.删除镜像 docker镜像存储位置: /var/lib/docker 查看docker信息也可以查看保存位置 docker info 1.列出镜像 docker images -aa ...
- Unity基础-脚本的优化
脚本的优化 object pool 避免频繁的内存分配和gc噩梦(字符串相加?) 是否有必要都写在update里?分帧? 需要的只取一次 使用editor内赋值,而不是find 复杂的物理 复杂的数学 ...