首先使用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的增删改查的更多相关文章

  1. iOS CoreData (一) 增删改查

    代码地址如下:http://www.demodashi.com/demo/11041.html Core Data是iOS5之后才出现的一个框架,本质上是对SQLite的一个封装,它提供了对象-关系映 ...

  2. CoreData之增删改查

    1. 导入库文件CoreData.framework2. 在iOS的Core Data 中建Data Model文件 此时有三种选择 2.1. 选Data Model(如默认名Model.xcdata ...

  3. iOS CoreData 增删改查详解

    最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...

  4. IOS之分析网易新闻存储数据(CoreData的使用,增删改查)

    用过网易新闻客户端的朋友们都知道,获取新闻列表时有的时候他会请求网络有时候不会,查看某条新闻的时候再返回会标注已经查看的效果,接下来分析一下是如何实现的. 首先: 1.网易新闻用CoreData存储了 ...

  5. CoreData的简单使用(二)数据的增删改查,轻量级的版本迁移

    上一篇中我们已经使用CoreData创建了一个SQLite数据库 CoreData的简单使用(一)数据库的创建 现在对数据库进行数据的CRUD(增删改查) 1.Data Model 的设置 创建一个D ...

  6. CoreData 从入门到精通(二) 数据的增删改查

    在上篇博客中,讲了数据模型和 CoreData 栈的创建,那下一步就是对数据的操作了.和数据库一样,CoreData 里的操作也无非是增删改查.下面我们将逐步讲解在 CoreData 中进行增删改查的 ...

  7. IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)

    1>什么是CoreData Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数 ...

  8. Dapper逆天入门~强类型,动态类型,多映射,多返回值,增删改查+存储过程+事物案例演示

    Dapper的牛逼就不扯蛋了,答应群友做个入门Demo的,现有园友需要,那么公开分享一下: 完整Demo:http://pan.baidu.com/s/1i3TcEzj 注 意 事 项:http:// ...

  9. ASP.NET从零开始学习EF的增删改查

           ASP.NET从零开始学习EF的增删改查           最近辞职了,但是离真正的离职还有一段时间,趁着这段空档期,总想着写些东西,想来想去,也不是很明确到底想写个啥,但是闲着也是够 ...

随机推荐

  1. Github删除项目

    相关博客:GitLab删除项目操作 发现github的项目删除按钮挺难找的,记录一下. 1,先在github打开项目,进入项目 2,点击Settings,进去后往下拉就是删除按钮.

  2. 分布式_理论_02_Base 理论

    一.前言 五.参考资料 1.分布式理论(二)——Base 理论 2.分布式理论(二) - BASE理论

  3. json与DataTable相互转换

    首先我们看看 Newtonsoft.Json.JsonConvert 是怎么完成的: DataTable table = new DataTable(); table.Columns.Add(&quo ...

  4. BackBone 源码解读及思考

    说明 前段时间略忙,终于找到时间看看backbone代码. 正如知友们说的那样,backbone简单.随性. 代码简单的看一眼,就能知道作者的思路.因为简单,所以随性,可以很自由的和其他类库大搭配使用 ...

  5. python之ConfigParser的使用。

    一.ConfigParser简介 ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号“[ ]”内包含的为section.section 下面为类似于key-value 的配置 ...

  6. 图片上传-本地图片转base64+ie8支持+本地预览支持

    最近项目由于flash同学没在了,图片上传只能前端重新做,后台希望用base64数据上传,复用之前接口 问题来了, 1.ie8 不支持canvas转base64 2.本地预览 base64数据,ie8 ...

  7. Spring框架实现——远程方法调用RMI代码演示

    1.spring_RMI02_server服务端02 <?xml version="1.0" encoding="UTF-8"?> <bean ...

  8. LeetCode 4 Keys Keyboard

    原题链接在这里:https://leetcode.com/problems/4-keys-keyboard/description/ 题目: Imagine you have a special ke ...

  9. PCM音量控制

    http://blog.jianchihu.net/pcm-volume-control.html 一.声音的相关概念 声音是介质振动在听觉系统中产生的反应.声音总可以被分解为不同频率不同强度正弦波的 ...

  10. 在winform下实现左右布局多窗口界面的方法(二)

    这篇文章主要介绍了在winform下实现左右布局多窗口界面的方法之续篇 的相关资料,需要的朋友可以参考下 在上篇文章在winform下实现左右布局多窗口界面的方法(一)已经实现了左右布局多窗口界面,今 ...