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(/ ...
随机推荐
- Mycat实现读写分离、分库分表
系统开发中,数据库是非常重要的一个点.除了程序的本身的优化,如:SQL语句优化.代码优化,数据库的处理本身优化也是非常重要的.主从.热备.分表分库等都是系统发展迟早会遇到的技术问题问题.Mycat是一 ...
- 安全错误使用CORS在IE10与Node和Express及XMLHttpRequest: 网络错误 0x4c7, 操作已被用户取消
在IE下:VUE项目,后台替换为https请求之后,vue热更新请求挂起,控制台报错:XMLHttpRequest: 网络错误 0x4c7, 操作已被用户取消.但是chrome与Firefox正常 当 ...
- 中英文字符串截取函数msubstr
Thinkphp内置了一个可以媲美smarty的模板引擎,给我们带来了很大的方便.调用函数也一样,可以和smarty一样调用自己需要的函数,而官方也内置了一些常用的函数供大家调用. 比如今天我们说的截 ...
- Newtonsoft.Json初探
1.序列化 VehicleModelSearchingModel model = new VehicleModelSearchingModel() { brandId = , modelIds=&qu ...
- 作业题:闰年 if((year%4==0&&year%100!=0)||year&400==0)
作业题:闰年 if((year%4==0&&year%100!=0)||year&400==0)
- UI Testing in Xcode 7
参考文章: UI Testing in Xcode - WWDC 2015https://developer.apple.com/videos/play/wwdc2015-406/ Document ...
- 前端应该如何去认识http
大家应该都知道http是什么吧,肯定会回答不就是浏览器地址那东西吗,有啥好说的,接下来咱们来深入刨析下http这东西. 什么叫http:超文本传输协议(HTTP)是用于传输诸如HTML的超媒体文档的应 ...
- Java-JFrame窗体美化
Java-JFrame窗体美化 JFrame默认的窗体比较土,可以通过一定的美化,让窗体表现的比较漂亮,具体要根据设计的设计图进行美化: JFrame美化的大致思路:先将JFrame去除默认美化效果, ...
- v2ex站长专访 - 100offer专访Livid:不仅仅是V站站长
转载自: https://www.douban.com/group/topic/121611313/ 前几天上网时偶然发现v2ex站长的blog(https://livid.v2ex.com/),了解 ...
- vsftpd服务安装与虚拟用户配置
vsftpd的全名是“Very secure FTP Daemon” 一.安装vsftpd安装db4-util用于生成认证文件 yum -y install db4-utils 安装vsftpd yu ...