http://blog.csdn.net/q199109106q/article/details/8563438

//
// MJViewController.m
// 数据存储5-Core Data
//
// Created by mj on 13-4-16.
// Copyright (c) 2013年 itcast. All rights reserved.
// #import "MJViewController.h"
#import <CoreData/CoreData.h>
#import "NSString+File.h"
#import "Person.h" @interface MJViewController ()
@property (nonatomic, retain) NSManagedObjectContext *context;
@end @implementation MJViewController - (void)viewDidLoad
{
[super viewDidLoad]; // 初始化上下文对象
[self initContext]; // 插入数据
//[self addData];
//[self addPerson]; // 删除数据
//[self deleteData]; // 查询数据
[self findPerson]; // 更改数据
//[self updateData];
} - (void)dealloc {
[_context release];
[super dealloc];
} #pragma mark 查询数据
- (void)findPerson {
// 初始化查询对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (Person *person in array) {
NSLog(@"name=%@,age=%@", person.name, person.age);
}
} #pragma mark 插入数据
- (void)addPerson {
// 初始化一个跟上下文关联的对象
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context]; person.name = @"mj";
person.age = [NSNumber numberWithInt:]; [self.context save:nil];
} #pragma mark 删除数据
- (void)deleteData {
// 初始化查询对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; // 设置条件过滤 where age < 50
request.predicate = [NSPredicate predicateWithFormat:@"age < %i", ]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (NSManagedObject *person in array) {
// 删除掉的person对象就不会跟context关联了
[self.context deleteObject:person];
} // 将所有跟上下文相关联的对象同步到数据库
[self.context save:nil];
} #pragma mark 查询数据
- (void)updateData {
// 初始化查询对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; // 设置条件过滤 where age > 20
request.predicate = [NSPredicate predicateWithFormat:@"age > %i", ]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (NSManagedObject *person in array) {
[person setValue:[NSNumber numberWithInt:] forKey:@"age"];
} // 将所有跟上下文相关联的对象同步到数据库
[self.context save:nil];
} #pragma mark 查询数据
- (void)findData { // 初始化查询对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; // 按照age降序
NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO]; request.sortDescriptors = [NSArray arrayWithObject:desc]; // 设置条件过滤 where age > 20
//request.predicate = [NSPredicate predicateWithFormat:@"age > %i", 20]; // name like '%j-1%'
//request.predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*j-1*"]; NSArray *array = [self.context executeFetchRequest:request error:nil]; for (NSManagedObject *person in array) {
NSString *name = [person valueForKey:@"name"]; int age = [[person valueForKey:@"age"] intValue]; NSLog(@"name=%@,age=%i", name, age);
} } #pragma mark 插入数据
- (void)addData {
//[[NSManagedObject alloc] initWithEntity:<#(NSEntityDescription *)#> insertIntoManagedObjectContext:<#(NSManagedObjectContext *)#>]; for (int i = ; i<; i++) {
// 初始化一个跟上下文关联的对象
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context]; // 设置对象的属性
[person setValue:[NSNumber numberWithInt:+i] forKey:@"age"];
NSString *name = [NSString stringWithFormat:@"mj-%i", i];
[person setValue:name forKey:@"name"];
} // 将所有跟上下文相关联的对象同步到数据库
[self.context save:nil];
} #pragma mark 初始化上下文对象
- (void)initContext {
// 1.加载模型文件
// nil代表从应用程序主bundle里面加载模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil] ; // 2.初始化持久化存储调度器
NSPersistentStoreCoordinator *store = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model] autorelease]; // 添加持久化存储库(这里用数据库存储)
NSString *path = [@"coredata.db" documentsAppend]; NSURL *url = [NSURL fileURLWithPath:path]; // 一定要给指针赋值
NSError *error = nil;
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]; if (error) {
NSLog(@"打开数据库失败:%@", [error localizedDescription]);
return;
} // 3.初始化上下文对象
self.context = [[[NSManagedObjectContext alloc] init] autorelease];
self.context.persistentStoreCoordinator = store;
} @end

下面是面向模型

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Person.h"
#import "Car.h"
@interface ViewController () @property(nonatomic,retain)NSManagedObjectContext *context;
@end @implementation ViewController - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. //从应用程序加载模型文件
NSManagedObjectModel *model=[NSManagedObjectModel mergedModelFromBundles:nil];
//传入模型对象,初始化NSPersistentStoreCoordinator对象
NSPersistentStoreCoordinator *psc=[[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model] autorelease];
//构建sqlite数据库文件的路径
NSString *docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSURL *url=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.db"]];
NSError *error=nil; if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]) { //[NSException raise:@"创建数据库失败" format:@"%@",[error localizedDescription]];
NSLog(@"创建数据库失败-->%@",[error localizedDescription]);
} self.context=[[NSManagedObjectContext alloc] init];
self.context.persistentStoreCoordinator=psc;
[_context release]; } - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (IBAction)addclick:(id)sender {
Person *person=[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
person.name=@"gcb111";
person.age=@; Car *car=[NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:self.context];
//[car setValue:@"123456789456" forKey:@"no"];
car.no=@"ssss111111"; car.person=person; NSError *error=nil;
[self.context save:&error];
if(error){
NSLog(@"-->同步失败-->%@",error.localizedDescription);
}
else{
NSLog(@"--->同步成功-->");
}
} - (IBAction)selectClick:(id)sender { //创建查询请求
NSFetchRequest *request=[[NSFetchRequest alloc] init];
//获取请求的实体
request.entity=[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
NSSortDescriptor *sort=[[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
request.sortDescriptors=@[sort];
NSError *error=nil;
NSArray *arr=[self.context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"-->查询失败-%@",error.localizedDescription);
return;
}
for (Person *p in arr) {
NSLog(@"-->%@-->%@",p.name,p.age);
} } - (IBAction)UpdateClick:(id)sender {
NSArray *arr=[self queryByAge:];
for (Person *p in arr) {
p.age=@;
}
NSError *error=nil;
[self.context save:&error];
if (error) {
NSLog(@"-->失败-%@",error); }
} - (IBAction)DelClick:(id)sender { NSArray *arr=[self queryByAge:];
for (Person *p in arr) {
[self.context deleteObject:p];
}
NSError *error=nil;
[self.context save:&error];
if (error) {
NSLog(@"-->失败-%@",error); }
} -(NSArray *)queryByAge:(int)age{
NSFetchRequest *request=[[NSFetchRequest alloc] init];
request.entity=[NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context]; NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age=%i",age];
request.predicate=predicate;
NSError *error=nil;
NSArray *arr=[self.context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"-->查询失败-%@",error.localizedDescription);
return nil;
}
return arr;
}

ios中coredata的更多相关文章

  1. IOS中CoreData浅析

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

  2. iOS 中CoreData的简单使用

    原文链接:http://www.jianshu.com/p/4411f507dd9f 介绍:本文介绍的CoreData不在AppDelegate中创建,在程序中新建工程使用,即创建本地数据库,缓存数据 ...

  3. iOS中coreData的用法

    // // ViewController.m // coredatademo002 // // Created by ganchaobo on 13-6-29. // Copyright (c) 20 ...

  4. IOS学习:ios中的数据持久化初级(文件、xml、json、sqlite、CoreData)

    IOS学习:ios中的数据持久化初级(文件.xml.json.sqlite.CoreData) 分类: ios开发学习2013-05-30 10:03 2316人阅读 评论(2) 收藏 举报 iOSX ...

  5. QF——iOS中的数据库操作:SQLite数据库,第三方封装库FMDB,CoreData

    SQLite数据库: SQLite是轻量级的数据库,适合应用在移动设备和小型设备上,它的优点是轻量,可移植性强.但它的缺点是它的API是用C写的,不是面向对象的.整体来说,操作起来比较麻烦.所以,一般 ...

  6. iOS中的数据持久化方式

    iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data. 1.属性列表 涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults ...

  7. iOS 中有用的开源库

    youtube下载神器:https://github.com/rg3/youtube-dl vim插件:https://github.com/Valloric/YouCompleteMe vim插件配 ...

  8. iOS中常用的四种数据持久化技术

    iOS中的数据持久化方式,基本上有以下四种:属性列表 对象归档 SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults st ...

  9. iOS中常用的四种数据持久化方法简介

    iOS中常用的四种数据持久化方法简介 iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 ...

随机推荐

  1. LeetCode295-Find Median from Data Stream && 480. 滑动窗口中位数

    中位数是有序列表中间的数.如果列表长度是偶数,中位数则是中间两个数的平均值. 例如, [2,3,4] 的中位数是 3 [2,3] 的中位数是 (2 + 3) / 2 = 2.5 设计一个支持以下两种操 ...

  2. 【转载】神奇的css属性pointer-events

    绝对定位元素盖住链接或添加某事件handle的元素后,那么该链接的默认行为(页面跳转)或元素事件将不会被触发.现在Firefox3.6+/Safari4+/Chrome支持一个称为pointer-ev ...

  3. 与IE的战斗

    对第2版的改进,工作量几乎都在UI上,不断的写css,写js,还别说,总体挺愉快的.特别是把360浏览器用顺了之后,烦人的无法刷新问题也不能困扰我了,改了js或者css文件的话,只要清除一下缓存,就可 ...

  4. OpenGL book list

      From: https://www.codeproject.com/Articles/771225/Learning-Modern-OpenGL   A little guide about mo ...

  5. php获取网址

    #测试网址: http://localhost/blog/testurl.php?id=5 //获取域名或主机地址 echo $_SERVER['HTTP_HOST']."<br> ...

  6. php学习实例3

    新闻发布管理系统 路由器action.php <!DOCTYPE html> <html> <head> <title> </title> ...

  7. 【Android界面实现】使用PagerTabStrip实现有滑动标签的Viewpager

    在ViewPager这样的能够滑动的控件上,总是有非常多的文章能够做.上次的文章,我们实现了一个自己定义的ViewPager的指示器,这篇文章,我们主要是想利用Android自带的控件,实现一个指示器 ...

  8. springboot升级到2.0后context-path配置不起作用

    springboot升级到2.0后,context-path配置不起作用,改成了: server.servlet.context-path=/projname

  9. You have version null and I want version 8

    删除hdfs上的/hbasehadoop fs -rm -r /hbase 删除zookeeper上的/hbasezookeeper-client -server 192.168.1.2:2181 r ...

  10. Ganglia监控Hadoop集群的安装部署

    一. 安装环境 Ubuntu server 12.04 安装gmetad的机器:192.168.52.105 安装gmond的机器:192.168.52.31,192.168.52.32,192.16 ...