ios coreData使用
Core Data数据持久化是对SQLite的一个升级,它是ios集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类。
(1)NSManagedObjectModel(被管理的对象模型)
相当于实体,不过它包含 了实体间的关系
(2)NSManagedObjectContext(被管理的对象上下文)
操作实际内容
作用:插入数据 查询 更新 删除
(3)NSPersistentStoreCoordinator(持久化存储助理)
相当于数据库的连接器
(4)NSFetchRequest(获取数据的请求)
相当于查询语句
(5)NSPredicate(相当于查询条件)
(6)NSEntityDescription(实体结构)
(7)后缀名为.xcdatamodel的包
里面的.xcdatamodel文件,用数据模型编辑器编辑
编译后为.momd或.mom文件,这就是为什么文件中没有这个东西,而我们的程序中用到这个东西而不会报错的原因
首先我们要建立模型对象
其次我们要生成模型对象的实体User,它是继承NSManagedObjectModel的
点击之后你会发现它会自动的生成User,现在主要说一下,生成的User对象是这种形式的
这里解释一下dynamic 平常我们接触的是synthesize
dynamic和synthesize有什么区别呢?它的setter和getter方法不能自已定义
打开CoreData的SQL语句输出开关
1.打开Product,点击EditScheme...
2.点击Arguments,在ArgumentsPassed On Launch中添加2项
1> -com.apple.CoreData.SQLDebug
2> 1
- #import <UIKit/UIKit.h>
- #import <CoreData/CoreData.h>
- @class ViewController;
- @interface AppDelegate : UIResponder <UIApplicationDelegate>
- @property (strong, nonatomic) UIWindow *window;
- @property (strong, nonatomic) ViewController *viewController;
- @property(strong,nonatomic,readonly)NSManagedObjectModel* managedObjectModel;
- @property(strong,nonatomic,readonly)NSManagedObjectContext* managedObjectContext;
- @property(strong,nonatomic,readonly)NSPersistentStoreCoordinator* persistentStoreCoordinator;
- @end
- #import "AppDelegate.h"
- #import "ViewController.h"
- @implementation AppDelegate
- @synthesize managedObjectModel=_managedObjectModel;
- @synthesize managedObjectContext=_managedObjectContext;
- @synthesize persistentStoreCoordinator=_persistentStoreCoordinator;
- - (void)dealloc
- {
- [_window release];
- [_viewController release];
- [_managedObjectContext release];
- [_managedObjectModel release];
- [_persistentStoreCoordinator release];
- [super dealloc];
- }
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
- // Override point for customization after application launch.
- self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
- self.window.rootViewController = self.viewController;
- [self.window makeKeyAndVisible];
- 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:.
- }
- //托管对象
- -(NSManagedObjectModel *)managedObjectModel
- {
- if (_managedObjectModel!=nil) {
- return _managedObjectModel;
- }
- // NSURL* modelURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"momd"];
- // _managedObjectModel=[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
- _managedObjectModel=[[NSManagedObjectModel mergedModelFromBundles:nil] retain];
- return _managedObjectModel;
- }
- //托管对象上下文
- -(NSManagedObjectContext *)managedObjectContext
- {
- if (_managedObjectContext!=nil) {
- return _managedObjectContext;
- }
- NSPersistentStoreCoordinator* coordinator=[self persistentStoreCoordinator];
- if (coordinator!=nil) {
- _managedObjectContext=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
- [_managedObjectContext setPersistentStoreCoordinator:coordinator];
- }
- return _managedObjectContext;
- }
- //持久化存储协调器
- -(NSPersistentStoreCoordinator *)persistentStoreCoordinator
- {
- if (_persistentStoreCoordinator!=nil) {
- return _persistentStoreCoordinator;
- }
- // NSURL* storeURL=[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreaDataExample.CDBStore"];
- // NSFileManager* fileManager=[NSFileManager defaultManager];
- // if(![fileManager fileExistsAtPath:[storeURL path]])
- // {
- // NSURL* defaultStoreURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"CDBStore"];
- // if (defaultStoreURL) {
- // [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
- // }
- // }
- NSString* docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
- NSURL* storeURL=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
- NSLog(@"path is %@",storeURL);
- NSError* error=nil;
- _persistentStoreCoordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
- if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
- NSLog(@"Error: %@,%@",error,[error userInfo]);
- }
- return _persistentStoreCoordinator;
- }
- //-(NSURL *)applicationDocumentsDirectory
- //{
- // return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
- //}
- @end
- #import <UIKit/UIKit.h>
- #import "AppDelegate.h"
- @interface ViewController : UIViewController
- @property (retain, nonatomic) IBOutlet UITextField *nameText;
- @property (retain, nonatomic) IBOutlet UITextField *ageText;
- @property (retain, nonatomic) IBOutlet UITextField *sexText;
- @property(nonatomic,retain)AppDelegate* myAppDelegate;
- - (IBAction)addIntoDataSource:(id)sender;
- - (IBAction)query:(id)sender;
- - (IBAction)update:(id)sender;
- - (IBAction)del:(id)sender;
- #import "ViewController.h"
- #import "User.h"
- @interface ViewController ()
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- _myAppDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (void)dealloc {
- [_nameText release];
- [_ageText release];
- [_sexText release];
- [super dealloc];
- }
- //插入数据
- - (IBAction)addIntoDataSource:(id)sender {
- User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
- [user setName:_nameText.text];
- [user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];
- [user setSex:_sexText.text];
- NSError* error;
- BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];
- if (!isSaveSuccess) {
- NSLog(@"Error:%@",error);
- }else{
- NSLog(@"Save successful!");
- }
- }
- //查询
- - (IBAction)query:(id)sender {
- NSFetchRequest* request=[[NSFetchRequest alloc] init];
- NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
- [request setEntity:user];
- // NSSortDescriptor* sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
- // NSArray* sortDescriptions=[[NSArray alloc] initWithObjects:sortDescriptor, nil];
- // [request setSortDescriptors:sortDescriptions];
- // [sortDescriptions release];
- // [sortDescriptor release];
- NSError* error=nil;
- NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
- if (mutableFetchResult==nil) {
- NSLog(@"Error:%@",error);
- }
- NSLog(@"The count of entry: %i",[mutableFetchResult count]);
- for (User* user in mutableFetchResult) {
- NSLog(@"name:%@----age:%@------sex:%@",user.name,user.age,user.sex);
- }
- [mutableFetchResult release];
- [request release];
- }
- //更新
- - (IBAction)update:(id)sender {
- NSFetchRequest* request=[[NSFetchRequest alloc] init];
- NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
- [request setEntity:user];
- //查询条件
- NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];
- [request setPredicate:predicate];
- NSError* error=nil;
- NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
- if (mutableFetchResult==nil) {
- NSLog(@"Error:%@",error);
- }
- NSLog(@"The count of entry: %i",[mutableFetchResult count]);
- //更新age后要进行保存,否则没更新
- for (User* user in mutableFetchResult) {
- [user setAge:[NSNumber numberWithInt:12]];
- }
- [_myAppDelegate.managedObjectContext save:&error];
- [mutableFetchResult release];
- [request release];
- }
- //删除
- - (IBAction)del:(id)sender {
- NSFetchRequest* request=[[NSFetchRequest alloc] init];
- NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
- [request setEntity:user];
- NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];
- [request setPredicate:predicate];
- NSError* error=nil;
- NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
- if (mutableFetchResult==nil) {
- NSLog(@"Error:%@",error);
- }
- NSLog(@"The count of entry: %i",[mutableFetchResult count]);
- for (User* user in mutableFetchResult) {
- [_myAppDelegate.managedObjectContext deleteObject:user];
- }
- if ([_myAppDelegate.managedObjectContext save:&error]) {
- NSLog(@"Error:%@,%@",error,[error userInfo]);
- }
- }
- @end
ios coreData使用的更多相关文章
- iOS CoreData技术学习资源汇总
一.CoreData学习指引 1. 苹果官方:Core Data Programming Guide 什么是CoreData? 创建托管对象模型 初始化Core Data堆栈 提取对象 创建和修改自定 ...
- IOS CoreData 多表查询demo解析
在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...
- iOS CoreData (一) 增删改查
代码地址如下:http://www.demodashi.com/demo/11041.html Core Data是iOS5之后才出现的一个框架,本质上是对SQLite的一个封装,它提供了对象-关系映 ...
- iOS CoreData (二) 版本升级和数据库迁移
前言:最近ChinaDaily项目需要迭代一个新版本,在这个版本中CoreData数据库模型上有新增表.实体字段的增加,那么在用户覆盖安装程序时就必须要进行CoreData数据库的版本升级和旧数据迁移 ...
- IOS CoreData 多表查询(下)
http://blog.csdn.net/fengsh998/article/details/8123392 在iOS CoreData中,多表查询上相对来说,没有SQL直观,但COREDATA的功能 ...
- iOS CoreData 介绍和使用(以及一些注意事项)
iOS CoreData介绍和使用(以及一些注意事项) 最近花了一点时间整理了一下CoreData,对于经常使用SQLite的我来说,用这个真的有点用不惯,个人觉得实在是没发现什么亮点,不喜勿喷啊.不 ...
- iOS CoreData介绍和使用(以及一些注意事项)
iOS CoreData介绍和使用(以及一些注意事项) 最近花了一点时间整理了一下CoreData,对于经常使用SQLite的我来说,用这个真的有点用不惯,个人觉得实在是没发现什么亮点,不喜勿喷啊.不 ...
- iOS - CoreData 数据库存储
1.CoreData 数据库 CoreData 是 iOS SDK 里的一个很强大的框架,允许程序员以面向对象的方式储存和管理数据.使用 CoreData 框架,程序员可以很轻松有效地通过面向对象的接 ...
- iOS coreData问题
iOS常见错误-CoreData: Cannot load NSManagedObjectModel.nil is an illegal URL parameter 这是因为在工程中CoreData的 ...
- ios Coredata 的 rollback undo 等事物处理函数
首先说明 ios 中 NSManagedObjectContext 默认的 undoManager是nil的,就是说 undo 和 redo 都是没用的. 但是 rollback函数和reset函数是 ...
随机推荐
- css的border效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- WP8_区分滑动和点击(在图片列表中)
在windows phone中,对于一个页面中 有图片列表的,滑动的时候,很容易被误认为是点击了图片,而打开图片详细信息等,原意是滑动列表,由此对图片添加2个事件,来控制其点击行为(滑动的时候,基本不 ...
- C# winform编程中多线程操作控件方法
private void Form1_Load(object sender, EventArgs e) { Thread newthread = new Thread(new ThreadStart( ...
- WEB跨域的实现
同源策略/SOP(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS.CSFR等攻击(可以参考我的这篇文章). SOP要求 ...
- 关于URL大小写问题
关于URL大小写的问题,不同平台的处理不同:Mac OS X 默认的文件系统(HFS case-insensitive) 是不分大小写的,Windows 上的 NTFS 也是,而 Linux 系统常用 ...
- C#中List〈string〉和string[]数组之间的相互转换
1,从System.String[]转到List<System.String> System.String[] str={"str","string" ...
- silverlight水印
1.自定义类 using System; using System.Net; using System.Windows; using System.Windows.Controls; using Sy ...
- Silverlight取得Session
首先Session是运行在服务器上的,而Silverlight运行在客户端.因此在Silverlight中使用SESSION的说法并不准确, 只因大家经常这样搜索才起这个名字. 有两种方法实现Silv ...
- ecshop常用语句
ecshop之中的IF语句: <select name="product_cat" id="product_cat" class="form-c ...
- 利用RecyclerView CardView实现新闻卡片样式
引入的包: demo结构: 测试代码: News.java: package com.zzw.testcardview; import java.io.Serializable; public cla ...