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(/ ...
随机推荐
- BCB:UTF8Encode、AnsiToUtf8
UTF8Encode: Call Utf8Encode to convert a Unicode string to UTF-8. WS is the Unicode string to conver ...
- targetcli save error
iscsi configuration unable to save python error “ValueError: 'Implict and Explict' is not in list” / ...
- 天坑之mysql乱码问题以及mysql重启出现1067的错误解决
相信很多小伙伴都遇到过数据库中文乱码问题,很头疼,明明Navicat上的编码格式都是utf-8是一样的啊? 为什么还是乱码? 原因是Navicat上的数据库编码格式并不是真正的编码格式 ,所以明白了吗 ...
- JavaScript学习整理(转载)
JavaScript的学习整理(一) 目录: 1.换皮肤功能2.显示/隐藏(点击切换)3.显示/隐藏(onmouseover/onmouseout)4.选项卡5.全选/不选/反选(checkbox)6 ...
- webgis技术在智慧城市综合治理(9+X)网格化社会管理平台(综治平台)的应用研究
综治中心9+X网格化社会管理平台 为落实中央关于加强创新社会治理的要求,适应国家治理体系和治理能力现代化要求,以基层党组织为核心,以整合资源.理顺关系.健全机制.发挥作用为目标,规范街道.社区综治中心 ...
- Core BlueTooth官方文档翻译
本⽂文是苹果<Core Bluetooth Programming Guide>的翻译. 关于Core Bluetooth Core Bluetooth 框架提供了蓝⽛牙低功耗⽆无线设备与 ...
- 【主席树】bzoj1112: [POI2008]砖块Klo
数据结构划一下水 Description N柱砖,希望有连续K柱的高度是一样的. 你可以选择以下两个动作 1:从某柱砖的顶端拿一块砖出来,丢掉不要了. 2:从仓库中拿出一块砖,放到另一柱.仓库无限大. ...
- pandas实践——美国人口分析
1.导入文件,并查看数据样本 abbr = pd.read_csv("./state-abbrevs.csv")areas =pd.read_csv("./state-a ...
- ubuntu : 无法安全地用该源进行更新,所以默认禁用该源。
sudo apt update报错: 无法安全地用该源进行更新,所以默认禁用该源. 1.检查是否是网络出了问题,修改DNS:114.114.114.114,8.8.8.8 断开网卡再重新连接,成功! ...
- Linux基础学习-网络管理
Linux系统网络管理NetworkManager 1 启动网络管理服务和开机自启动 在rhel7中网路管理相关命令nmcli,nmtui,nmtui-edit,nm-connection-edito ...