CoreData的增删改查
首先使用CoreData创建Demo,勾上CoreData选项

然后创建Entity对象,点击Add Entity(+)按钮

生成Entity对象

重命名双击Entity选项,然后输入Person

设置Person属性,点击Attributes选项中的+号,实现添加属性,并给属性命名,且添加属性相关的类型

然后command+N,创建NSManagedObject subclass

然后点击Next

然后勾上 CoreData_Demo选项,然再点击Next

接着勾上Person选项,再次点击Next

接下来,跟着系统的提示进行操作,最后生成Person类

下面是相关操作的代码
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.h实现文件的代码
#import "AppDelegate.h"
#import "RootViewController.h"
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[RootViewController alloc] init]; [self.window makeKeyAndVisible];
return YES;
} - (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.YXYC.Test_CoreData_Test" 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:@"Test_CoreData_Test" 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:@"Test_CoreData_Test.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
RootViewController.h头文件相关的代码
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end
RootViewController.h实现文件相关的代码
#import "RootViewController.h"
#import "AppDelegate.h"
@interface RootViewController () @property (strong, nonatomic) AppDelegate *appDelegate; @end @implementation RootViewController - (void)viewDidLoad {
[super viewDidLoad];
self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// 存储数据
[self saveData];
// 查询全部数据
[self readData];
NSMutableArray *datas = [[NSMutableArray alloc] init];
// 得到查询的结果(条件查询)
datas = [self getObjectsWithPredicate];
// 删除
[self removeObjects];
// 修改
[self changeObjects];
} /**
* 存储数据
*/
- (void)saveData
{
NSManagedObjectContext *object = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
[object setValue:@"GL" forKey:@"name"];
[object setValue:@"female" forKey:@"sex"]; } /**
* 查询全部数据
*/
- (void)readData
{
// 实例化一个查询(Fetch)请求
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *object = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
[fetch setEntity:object]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSLog(@"sort:%@",sort); NSArray *sortarr = [[NSArray alloc] initWithObjects:sort, nil];
[fetch setSortDescriptors:sortarr]; NSError *error = nil;
// 让_context执行查询数据
NSArray *fetchresult = [self.appDelegate.managedObjectContext executeFetchRequest:fetch error:&error]; for (NSManagedObject *object in fetchresult) {
NSLog(@"name:%@==sex:%@",[object valueForKey:@"name"],[object valueForKey:@"sex"]);
} }
/**
* 条件查询
*
* @return 查询结果的Entity数组
*/
- (NSMutableArray *)getObjectsWithPredicate
{
NSError *error = nil;
// 实例化一个查询(Fetch)请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
// 条件查询
request.predicate = [NSPredicate predicateWithFormat:@"sex LIKE '*female'"];
// 让_context执行查询数据
NSArray *array = [self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
return [NSMutableArray arrayWithArray:array];
}
/**
* 删除操作
*/
- (void)removeObjects
{
NSError *error = nil;
// 实例化查询请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
// 设置条件
request.predicate = [NSPredicate predicateWithFormat:@"name = 'LF'"];
// 由上下文查询数据
NSArray *result =[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
// 打印条件结果,并删除对象
for (NSManagedObject *object in result) {
// 删除对象
[self.appDelegate.managedObjectContext deleteObject:object];
}
// 删除后,保存数据
[self.appDelegate.managedObjectContext save:&error];
}
/**
* 修改
*/
- (void)changeObjects
{
NSError *error = nil;
// 实例化查询请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
// 设置条件
request.predicate = [NSPredicate predicateWithFormat:@"name = 'GL'"];
// 由上下文查询数据
NSArray *result =[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error];
// 修改对象
for (NSManagedObject *object in result) {
// 修改对象
[object setValue:@"GYL" forKey:@"name"];
}
// 修改后,保存数据
[self.appDelegate.managedObjectContext save:&error];
} @end
CoreData的增删改查的更多相关文章
- iOS CoreData (一) 增删改查
代码地址如下:http://www.demodashi.com/demo/11041.html Core Data是iOS5之后才出现的一个框架,本质上是对SQLite的一个封装,它提供了对象-关系映 ...
- CoreData之增删改查
1. 导入库文件CoreData.framework2. 在iOS的Core Data 中建Data Model文件 此时有三种选择 2.1. 选Data Model(如默认名Model.xcdata ...
- iOS CoreData 增删改查详解
最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...
- IOS之分析网易新闻存储数据(CoreData的使用,增删改查)
用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的. 首先: 1.网易新闻用CoreData存储了 ...
- CoreData的简单使用(二)数据的增删改查,轻量级的版本迁移
上一篇中我们已经使用CoreData创建了一个SQLite数据库 CoreData的简单使用(一)数据库的创建 现在对数据库进行数据的CRUD(增删改查) 1.Data Model 的设置 创建一个D ...
- CoreData 从入门到精通(二) 数据的增删改查
在上篇博客中,讲了数据模型和 CoreData 栈的创建,那下一步就是对数据的操作了.和数据库一样,CoreData 里的操作也无非是增删改查.下面我们将逐步讲解在 CoreData 中进行增删改查的 ...
- IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)
1>什么是CoreData Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数 ...
- Dapper逆天入门~强类型,动态类型,多映射,多返回值,增删改查+存储过程+事物案例演示
Dapper的牛逼就不扯蛋了,答应群友做个入门Demo的,现有园友需要,那么公开分享一下: 完整Demo:http://pan.baidu.com/s/1i3TcEzj 注 意 事 项:http:// ...
- ASP.NET从零开始学习EF的增删改查
ASP.NET从零开始学习EF的增删改查 最近辞职了,但是离真正的离职还有一段时间,趁着这段空档期,总想着写些东西,想来想去,也不是很明确到底想写个啥,但是闲着也是够 ...
随机推荐
- 剑指offer--17.第一个只出现一次的字符
map默认对key进行排序,unordered_map不对键或值进行排序,但是也不是默认插入的顺序 -------------------------------------------------- ...
- grep---Linux下文本处理五大神器之五
转自:http://www.cnblogs.com/dong008259/archive/2011/12/12/2285264.html grep是linux中很常用的一个命令,主要功能就是进行字符串 ...
- CODE FESTIVAL 2017 qual A--B-fLIP(换种想法,暴力枚举)
个人心得:开始拿着题目还是有点懵逼的,以前做过相同的,不过那是按一个位置行列全都反之,当时也是没有深究.现在在打比赛不得不 重新构思,后面一想把所有的状态都找出来,因为每次确定了已经按下的行和列后,按 ...
- JvisualVm添加远程监控
一.Weblogic远程监控 1.首先需要在远程的weblogic的域下面,找到/bin/ setDomainEnv.sh ,需要在此文件下加入如下内容: -Dcom.sun.management.j ...
- BZOJ4520:[CQOI2016]K远点对
浅谈\(K-D\) \(Tree\):https://www.cnblogs.com/AKMer/p/10387266.html 题目传送门:https://lydsy.com/JudgeOnline ...
- hdu 4336 Card Collector —— Min-Max 容斥
题目:http://acm.hdu.edu.cn/showproblem.php?pid=4336 bzoj 4036 的简单版,Min-Max 容斥即可. 代码如下: #include<cst ...
- IHE 官方网址有用资源介绍
实现标准: http://www.ihe.net/Technical_Frameworks/ 各个实现框架文档, 比如XDS,XCA,PIX,PDQ等 测试工具:http://www.ihe.net/ ...
- 关于web.xml不同版本之间的区别
一.Servlet 2.3 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3// ...
- centos 虚拟机联网
在windows主机安装centos虚拟机后,遇到虚拟机连接外网问题. 解决方案:http://blog.csdn.net/pang040328/article/details/12427359 经过 ...
- Django基础(四)
Form表单 Admin Django Form表单 django 中的form 一般有两种功能: 输入html 验证用户输入 1,先写一个form import re from django ...