- 浏览: 515546 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
tangyunliang:
大哥你太历害了谢谢
Android基于XMPP Smack Openfire开发IM【四】初步实现两个客户端通信 -
u013015029:
LZ,请问下,在// 添加消息到聊天窗口 , 这里获取Ed ...
Android基于XMPP Smack Openfire开发IM【四】初步实现两个客户端通信 -
endual:
怎么保持会话,我搞不懂啊
Android基于XMPP Smack Openfire开发IM【一】登录openfire服务器 -
donala_zq:
显示:[2013-11-30 11:50:36 - Andro ...
android-----------新浪微博 -
donala_zq:
哥,运行不了啊
android-----------新浪微博
实现的功能:1)演示使用CoreData持久化数据(仅显示基本操作,不包括很多复杂的操作)。
关键词:数据持久化 CoreData
1、新建一空工程,命名为:Persistence_CoreData:
[img]
[/img]
[img]
[/img]
2、选中“Use Core Data”后创建的工程中,AppDelegate.h中多了三个property,如下:
代码解释
//备注1
NSManagedObjectContext:相当于数据库操作
NSManagedObjectModel:相当于数据库中的表及它们之间的关系
persistentStoreCoordinator:相当于数据库存放方式
以上比较不一定准确,但是可以更容易理解CoreData的应用。
3、AppDelegate.m中多了三个方法,如下:
//备注2
//这三个方法,对应返回备注1中声明的3个变量
4、新建视图控制器ViewController(带xib)
[img]
[/img]
修改AppDelegate.m中- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
设置根视图控制器
5、修改ViewController.xib,如下:
[img]
[/img]
6、修改Persistence_CoreData.xcdatamodeld,添加Entity,名称为User,如下
[img]
[/img]
7、修改ViewController,ViewController.h如下:
ViewController.m如下:
//备注3
//通过 delegate调用方法managedObjectContext,得到NSManagedObjectContext对象,
//NSManagedObjectContext对象会跟NSPersistentStoreCoordinator对象交互,NSPersistentStoreCoordinator对象负责处理底层的存储,sqlite3数据库名称默认为工程名称,Persistence_CoreData.sqlite
8、CoreData使用的数据库存储的位置是:
/Users/duobianxing/Library/Application Support/iPhone Simulator/5.0/Applications/BCCE1DDC-F50F-4A52-9678-991AC6DFBC7C/Documents
[img]
[/img]
虽然该博文演示的创建“Use Core Data”的工程,其实只要搞明白选中“Use Core Data”后该工程模板都添加了哪些内容以及其作用?那么在一个已存在的工程(没有使用CorData)的加入CoreData的支持也非常方便。
关键词:数据持久化 CoreData
1、新建一空工程,命名为:Persistence_CoreData:
[img]
[/img]
[img]
[/img]
2、选中“Use Core Data”后创建的工程中,AppDelegate.h中多了三个property,如下:
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; //备注1 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; - (void)saveContext; - (NSURL *)applicationDocumentsDirectory; @end
代码解释
//备注1
NSManagedObjectContext:相当于数据库操作
NSManagedObjectModel:相当于数据库中的表及它们之间的关系
persistentStoreCoordinator:相当于数据库存放方式
以上比较不一定准确,但是可以更容易理解CoreData的应用。
3、AppDelegate.m中多了三个方法,如下:
#import "AppDelegate.h" #import "ViewController.h" @implementation AppDelegate @synthesize managedObjectContext = _managedObjectContext; @synthesize managedObjectModel = _managedObjectModel; @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. //设置根视图控制器 self.window.rootViewController = [[ViewController alloc]initWithNibName:@"ViewController" bundle:nil]; self.window.backgroundColor = [UIColor whiteColor]; [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 { // Saves changes in the application's managed object context before the application terminates. [self saveContext]; } - (void)saveContext { NSError *error = nil; NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != 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(); } } } //备注2
#pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. - (NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext; } // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Persistence_CoreData" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; } // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Persistence_CoreData.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] * Performing automatic lightweight migration by passing the following dictionary as the options parameter: @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; } #pragma mark - Application's Documents directory // Returns the URL to the application's Documents directory. - (NSURL *)applicationDocumentsDirectory { return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; } @end
//备注2
//这三个方法,对应返回备注1中声明的3个变量
4、新建视图控制器ViewController(带xib)
[img]
[/img]
修改AppDelegate.m中- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
设置根视图控制器
5、修改ViewController.xib,如下:
[img]
[/img]
6、修改Persistence_CoreData.xcdatamodeld,添加Entity,名称为User,如下
[img]
[/img]
7、修改ViewController,ViewController.h如下:
#import <UIKit/UIKit.h> #import "AppDelegate.h" @interface ViewController : UIViewController{ AppDelegate *appDelegate; } @property(strong,nonatomic)IBOutlet UITextField *serverIp; @property(strong,nonatomic)IBOutlet UITextField *userName; @end
ViewController.m如下:
#import "ViewController.h" #import "AppDelegate.h" @interface ViewController () @end @implementation ViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. //获取App代理 appDelegate = [[UIApplication sharedApplication] delegate]; //订阅通知 UIApplication *app = [UIApplication sharedApplication]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app]; [self loadData]; } //加载数据 -(void)loadData{ //1)获取托管对象上下文(相当于数据库操作) NSManagedObjectContext *context = [appDelegate managedObjectContext];//备注3 //2)创建NSFetchRequest对象(相当于数据库中的SQL语句) NSFetchRequest *request = [[NSFetchRequest alloc] init]; //3)创建查询实体(相当于数据库中要查询的表) NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context]; //设置查询实体 [request setEntity:entityDescription]; //4)创建排序描述符,ascending:是否升序(相当于数据库中排序设置)。此处仅为演示,本实例不需要排序 NSSortDescriptor *sortDiscriptor = [[NSSortDescriptor alloc] initWithKey:@"userName" ascending:NO]; NSArray *sortDiscriptos = [[NSArray alloc] initWithObjects:sortDiscriptor, nil]; [request setSortDescriptors:sortDiscriptos]; //5)创建查询谓词(相当于数据库中查询条件) 此处仅为演示,本实例不需要查询条件 NSPredicate *pred = [NSPredicate predicateWithFormat:@"(serverIp like %@)",@"192"]; [request setPredicate:pred]; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error]; if(objects == nil){ NSLog(@"There has a error!"); //做错误处理 }else{ if([objects count]>0){ NSManagedObject *oneObject = [objects objectAtIndex:0]; NSString *serverIp = [oneObject valueForKey:@"serverIp"]; NSString *userName = [oneObject valueForKey:@"userName"]; self.serverIp.text = serverIp; self.userName.text = userName; } } } //应用界面退出时,保存数据 -(void)applicationWillResignActive:(NSNotification *)notification{ NSLog(@"applicationWillResignActive"); //创建托管对象上下文 NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc]init]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context]; [request setEntity:entityDescription]; NSManagedObject *user = nil; NSError *error; NSArray *objets = [context executeFetchRequest:request error:&error]; if(objets==nil){ NSLog(@"There has a error!"); //做错误处理 } if([objets count]>0){ //非第一次,更新数据 NSLog(@"更新操作"); user = [objets objectAtIndex:0]; }else{ NSLog(@"插入操作"); //第一次保存,插入新数据 user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context]; } [user setValue:self.serverIp.text forKeyPath:@"serverIp"]; [user setValue:self.userName.text forKeyPath:@"userName"]; [context save:&error]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
//备注3
//通过 delegate调用方法managedObjectContext,得到NSManagedObjectContext对象,
//NSManagedObjectContext对象会跟NSPersistentStoreCoordinator对象交互,NSPersistentStoreCoordinator对象负责处理底层的存储,sqlite3数据库名称默认为工程名称,Persistence_CoreData.sqlite
8、CoreData使用的数据库存储的位置是:
/Users/duobianxing/Library/Application Support/iPhone Simulator/5.0/Applications/BCCE1DDC-F50F-4A52-9678-991AC6DFBC7C/Documents
[img]
[/img]
虽然该博文演示的创建“Use Core Data”的工程,其实只要搞明白选中“Use Core Data”后该工程模板都添加了哪些内容以及其作用?那么在一个已存在的工程(没有使用CorData)的加入CoreData的支持也非常方便。
发表评论
-
新风作浪博客学习(十九)在iOS虚拟键盘上添加动态隐藏按钮
2013-06-08 09:19 814为了给用户比较良好的交付,想在键盘上添加一个按钮,实时根据键盘 ... -
新风作浪博客学习(十八)openURL的使用(iOS调用系统电话、浏览器、地图、邮件等) .
2013-06-08 09:19 930今天遇见一行代码实现打开一个网页,比起印象里的UIWebVie ... -
新风作浪博客学习(十七)UIImageView响应点击事件 .
2013-06-08 09:19 664有时候会遇到点击一张图片,然后让这张图片触发一个事件,或者是跳 ... -
新风作浪博客学习(十六)Navigation + Tab Bar 常用组合框架 .
2013-06-07 08:50 1191看到很多项目中都采用的是Navigation加Tab Bar组 ... -
新风作浪博客学习(十五)google地图定位小Demo .
2013-06-07 08:50 1057[img][/img]今天写的是一个简单功能的google地图 ... -
新风作浪博客学习(十四)怎样向iPhone模拟器中添加图片 .
2013-06-07 08:50 740在我们做项目中可能需要使用图库,模拟器是有图库的,但是如何像其 ... -
新风作浪博客学习(十三)表视图的分组分区和索引分区 .
2013-06-07 08:50 742本次实现的是表视图的分区和索引,代码和前面都差不多,主要还是代 ... -
新风作浪博客学习(十二)代码实现UITableViewCell表视图单元定制 .
2013-06-07 08:49 928通常情况下我们会希望单元格UITableViewCell显示自 ... -
新风作浪博客学习(十一)UITableViewCell的标记、移动、删除、插入 .
2013-06-06 09:15 1055这篇文章是建立在 代码实现 UITableView与UITa ... -
新风作浪博客学习(十)代码实现 UITableView与UITableViewCell .
2013-06-06 09:14 1108我们常用的表格类视图就是用 UITableView与UITab ... -
新风作浪博客学习(九)两个UIPickerView控件间的数据依赖 .
2013-06-06 09:14 1039本篇实现功能是两个选取器的关联操作,滚动第一个滚轮第二个滚 ... -
新风作浪博客学习(八)代码实现UIPickerView .
2013-06-06 09:14 1237先说一下当个组件选取器,我们创建一个数组NSAray来保存选取 ... -
新风作浪博客学习(七)代码 实现UIDatePicker控件 和 Tab Bar 视图切换 .
2013-06-06 09:15 1068感觉代码写控件都一个理,先在ViewDidLoad中创建控件对 ... -
新风作浪博客学习(六)ios 视图切换翻页效果 .
2013-06-05 11:18 1020本文写的是视图切换,涉及到的内容有 1.实现代码添加Navi ... -
新风作浪博客学习(五)代码实现UISlider 和 UISwitch .
2013-02-18 09:15 1072本次实现的UISlider和UISwi ... -
新风作浪博客学习(四)把plist里数据显示在textField上 .
2013-02-18 09:15 881在代码实现Lable 、textFie ... -
新风作浪博客学习(三)NSBundle读取图片 plist文件和txt文件
2013-02-18 09:15 1622本文想简单介绍一下NSBundle读取图片到视图上,读取pli ... -
新风作浪博客学习(二)代码实现Lable 、textField创建界面以及键盘的处理
2013-02-18 09:15 1137今天写的是用代码实现一个简单界面,代码重复率比较高,可读性不是 ... -
新风作浪博客学习(一)plist文件读写操作
2013-02-18 09:14 1297文件plist 全名Property List,属性列表文件, ... -
GCDiscreetNotificationView提示视图
2013-06-05 11:17 523先看一下效果图: [img] ...
相关推荐
ios 数据存储,数据持久化,包含Preference 、文件存储、归档、数据库 、 CoreData的使用
coreData数据方法.rar此文件可以直接运行,里面包括怎么建立模型,怎么写入数据以及取出数据
python库。 资源全名:coredata-0.1.5.tar.gz
使用CoreData开发iPhone手机应用软件的实例教程.pdf
方便使用的 CoreData 1.导入 CoreData 框架,引入头文件 2.创建数据的模型文件 3.读取数据库的模型文件 4.创建持久化的数据文件
CoreData 数据存储
沙盒 和 数据持久化存储 Core Data 和 NSUserDefaults 案例
coredata是iOS系统提供用于对象化管理数据并且持久化的框架,较于FMDB,coredata的优势:第一是CoreData作为苹果提供的原生框架,在内存方法比SQLite有性能上的优势。第二是CoreData操作数据不需要使用SQLite代码,...
对于coredata的简单封装,实现建表 增 删 改 查
使用CoreData开发iPhone手机应用软件的实例教程参考.pdf
Ionic-CoreData-源码.rar
通过一段具体的代码演示了CoreData如何验证输入数据是否满足要求
本demo是数据持久化的一种CoreData,对CoreData进行了封装,实现了增删改查
SQLite,FMDB,CoreData的小的例子。还有一个小的CALyer隐式动画的例子。
ios CoreData详细详细讲解,在OBJC.IO上购买的,价值96元,现在分享出去,下网能够帮助更多的人学习。
比较好的coredata资料,你值得拥有。。
swift_persistence.zip
CoreData数据存储demo
CoreData的添加删除,和分页查询,模拟查询聊天记录,加载数据时数据添加在上面且页面显示当前位置