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的增删改查 最近辞职了,但是离真正的离职还有一段时间,趁着这段空档期,总想着写些东西,想来想去,也不是很明确到底想写个啥,但是闲着也是够 ...
随机推荐
- Win7+VS2010下配置WTL开发环境
一.今天Win7下刚装了VS2010,解压wtl81_12085.zip到C盘根目录,进入C:\wtl81_12085\AppWiz下,执行setup100.js提示向导安装成功. 在VS2010中新 ...
- ie-9 以下ajax无法跨域的问题。只要add:jQuery.support.cors=true;即可
if (!jQuery.support.cors && window.XDomainRequest) { var httpRegEx = /^https?:\/\//i; var ge ...
- 【SQL查询】查询的列起别名_AS
方法一: 以as关键字指定字段别名,as在select的字段和别名之间. 方法二: 直接在字段名称后面加上别名,中间以空格隔开.
- redis3.2.11 安装
wget http://download.redis.io/releases/redis-3.2.11.tar.gz [root@hdp01 src]# .tar.gz -C /opt/ [root@ ...
- LeetCode Predict the Winner
原题链接在这里:https://leetcode.com/problems/predict-the-winner/description/ 题目: Given an array of scores t ...
- P1605 迷宫(洛谷)
题目背景 迷宫 [问题描述] 给定一个N*M方格的迷宫,迷宫里有T处障碍,障碍处不可通过.给定起点坐标和终点坐标,问: 每个方格最多经过1次,有多少种从起点坐标到终点坐标的方案.在迷宫中移动有上下左右 ...
- oracle获得当前时间,精确到毫秒并指定精确位数
oracle获得当前时间的,精确到毫秒 可以指定精确豪秒的位数 select to_char(systimestamp, 'yyyymmdd hh24:mi:ss.ff ') from dual; ...
- jslint报错太多的解决方式
当jslint 一个js的时候,有时候太多“错误”,导致报错:“Too many errors. (53% scanned).”而停止检查 js文件,此时我们还是想把整个js文件检查完毕的. 所以,看 ...
- 机器学习:决策树(CART 、决策树中的超参数)
老师:非参数学习的算法都容易产生过拟合: 一.决策树模型的创建方式.时间复杂度 1)创建方式 决策树算法 既可以解决分类问题,又可以解决回归问题: CART 创建决策树的方式:根据某一维度 d 和某一 ...
- Resque基本
原文:http://www.cnblogs.com/rywx/archive/2012/05/26/2519615.html Resque resque是基于redis的后台任务组件,能把任何类或模块 ...