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(/ ...
随机推荐
- vue跨域处理(vue项目中baseUrl设置问题)
1.开发环境: 2.生产环境: 然后 const instance = axios.create({ baseURL: process.env.API })
- WPF DataGridCheckBoxColumn需要点两次才能修改checkbox状态
如题,如果必须要用DataGridCheckBoxColumn使用一下方式就可以解决需要点击两次才能改状态的问题 <DataGridCheckBoxColumn> <DataGrid ...
- if...else...这段代码打印结果,并简述其理由
var age = 20; if (age >= 6) { console.log('teenager'); } else if (age >= 18) { console.log('ad ...
- C++系统学习之九:顺序容器
元素在顺序容器中的顺序与其加入容器时的位置相对应.关联容器中元素的位置由元素相关联的关键字值决定.所有容器类都共享公共的接口,不同容器按不同方式对其进行扩展. 一个容器就是一些特定类型对象的集合.顺序 ...
- sphinx 快速使用
建立配置文件 例可以参照之前的模板新建一个配置文件 sphinx/etc目录 #MySQL数据源配置,详情请查看:http://www.coreseek.cn/products-install/mys ...
- tomcat报错:java.io.IOException: 您的主机中的软件中止了一个已建立的连接。
tomcat报错: org.apache.catalina.connector.ClientAbortException: java.io.IOException: 您的主机中的软件中止了一个已建立的 ...
- DeepFaceLab小白入门(4):提取人脸图片!
通过上面级片文章,你应该基本知道了换脸的流出,也能换出一个视频来.此时,你可能会产生好多疑问,比如每个环节点点到底是什么意思,那些黑漆漆屏幕输出的又是什么内容,我换脸效果这么差,该如何提升?等等,好奇 ...
- python3 完全平方数(循环)
题目 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? 代码: for i in range(1,85): if 168 % i == 0: j = 168 ...
- JDK1.8 HashMap$TreeNode.balanceInsertion 红黑树平衡插入
红黑树介绍 1.节点是红色或黑色. 2.根节点是黑色. 3.每个叶子节点都是黑色的空节点(NIL节点). 4 每个红色节点的两个子节点都是黑色.(从每个叶子到根的所有路径上不能有两个连续的红色节点) ...
- poj 3614 奶牛美容问题 优先队列
题意:每头奶牛需要涂抹防晒霜,其中有效的范围 min~max ,现在有L种防晒霜,每种防晒霜的指数为 f 瓶数为 l,问多少只奶牛可以涂上合适的防晒霜?思路: 优先队列+贪心 当奶牛的 min< ...