ios中的coredata

本文转载至 http://blog.csdn.net/chen505358119/article/details/9334831

分类: ios2013-07-15 18:12 12449人阅读 评论(0) 收藏 举报

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

[plain] view plaincopyprint?

  1. #import <UIKit/UIKit.h>
  2. #import <CoreData/CoreData.h>
  3. @class ViewController;
  4. @interface AppDelegate : UIResponder <UIApplicationDelegate>
  5. @property (strong, nonatomic) UIWindow *window;
  6. @property (strong, nonatomic) ViewController *viewController;
  7. @property(strong,nonatomic,readonly)NSManagedObjectModel* managedObjectModel;
  8. @property(strong,nonatomic,readonly)NSManagedObjectContext* managedObjectContext;
  9. @property(strong,nonatomic,readonly)NSPersistentStoreCoordinator* persistentStoreCoordinator;
  10. @end

[plain] view plaincopyprint?

  1. #import "AppDelegate.h"
  2. #import "ViewController.h"
  3. @implementation AppDelegate
  4. @synthesize managedObjectModel=_managedObjectModel;
  5. @synthesize managedObjectContext=_managedObjectContext;
  6. @synthesize persistentStoreCoordinator=_persistentStoreCoordinator;
  7. - (void)dealloc
  8. {
  9. [_window release];
  10. [_viewController release];
  11. [_managedObjectContext release];
  12. [_managedObjectModel release];
  13. [_persistentStoreCoordinator release];
  14. [super dealloc];
  15. }
  16. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  17. {
  18. self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
  19. // Override point for customization after application launch.
  20. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
  21. self.window.rootViewController = self.viewController;
  22. [self.window makeKeyAndVisible];
  23. return YES;
  24. }
  25. - (void)applicationWillResignActive:(UIApplication *)application
  26. {
  27. // 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.
  28. // 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.
  29. }
  30. - (void)applicationDidEnterBackground:(UIApplication *)application
  31. {
  32. // 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.
  33. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  34. }
  35. - (void)applicationWillEnterForeground:(UIApplication *)application
  36. {
  37. // 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.
  38. }
  39. - (void)applicationDidBecomeActive:(UIApplication *)application
  40. {
  41. // 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.
  42. }
  43. - (void)applicationWillTerminate:(UIApplication *)application
  44. {
  45. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  46. }
  47. //托管对象
  48. -(NSManagedObjectModel *)managedObjectModel
  49. {
  50. if (_managedObjectModel!=nil) {
  51. return _managedObjectModel;
  52. }
  53. //    NSURL* modelURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"momd"];
  54. //    _managedObjectModel=[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  55. _managedObjectModel=[[NSManagedObjectModel mergedModelFromBundles:nil] retain];
  56. return _managedObjectModel;
  57. }
  58. //托管对象上下文
  59. -(NSManagedObjectContext *)managedObjectContext
  60. {
  61. if (_managedObjectContext!=nil) {
  62. return _managedObjectContext;
  63. }
  64. NSPersistentStoreCoordinator* coordinator=[self persistentStoreCoordinator];
  65. if (coordinator!=nil) {
  66. _managedObjectContext=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
  67. [_managedObjectContext setPersistentStoreCoordinator:coordinator];
  68. }
  69. return _managedObjectContext;
  70. }
  71. //持久化存储协调器
  72. -(NSPersistentStoreCoordinator *)persistentStoreCoordinator
  73. {
  74. if (_persistentStoreCoordinator!=nil) {
  75. return _persistentStoreCoordinator;
  76. }
  77. //    NSURL* storeURL=[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreaDataExample.CDBStore"];
  78. //    NSFileManager* fileManager=[NSFileManager defaultManager];
  79. //    if(![fileManager fileExistsAtPath:[storeURL path]])
  80. //    {
  81. //        NSURL* defaultStoreURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"CDBStore"];
  82. //        if (defaultStoreURL) {
  83. //            [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
  84. //        }
  85. //    }
  86. NSString* docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
  87. NSURL* storeURL=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
  88. NSLog(@"path is %@",storeURL);
  89. NSError* error=nil;
  90. _persistentStoreCoordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  91. if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
  92. NSLog(@"Error: %@,%@",error,[error userInfo]);
  93. }
  94. return _persistentStoreCoordinator;
  95. }
  96. //-(NSURL *)applicationDocumentsDirectory
  97. //{
  98. //    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
  99. //}
  100. @end

[plain] view plaincopyprint?

  1. #import <UIKit/UIKit.h>
  2. #import "AppDelegate.h"
  3. @interface ViewController : UIViewController
  4. @property (retain, nonatomic) IBOutlet UITextField *nameText;
  5. @property (retain, nonatomic) IBOutlet UITextField *ageText;
  6. @property (retain, nonatomic) IBOutlet UITextField *sexText;
  7. @property(nonatomic,retain)AppDelegate* myAppDelegate;
  8. - (IBAction)addIntoDataSource:(id)sender;
  9. - (IBAction)query:(id)sender;
  10. - (IBAction)update:(id)sender;
  11. - (IBAction)del:(id)sender;

[plain] view plaincopyprint?

  1. #import "ViewController.h"
  2. #import "User.h"
  3. @interface ViewController ()
  4. @end
  5. @implementation ViewController
  6. - (void)viewDidLoad
  7. {
  8. [super viewDidLoad];
  9. // Do any additional setup after loading the view, typically from a nib.
  10. _myAppDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
  11. }
  12. - (void)didReceiveMemoryWarning
  13. {
  14. [super didReceiveMemoryWarning];
  15. // Dispose of any resources that can be recreated.
  16. }
  17. - (void)dealloc {
  18. [_nameText release];
  19. [_ageText release];
  20. [_sexText release];
  21. [super dealloc];
  22. }
  23. //插入数据
  24. - (IBAction)addIntoDataSource:(id)sender {
  25. User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
  26. [user setName:_nameText.text];
  27. [user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];
  28. [user setSex:_sexText.text];
  29. NSError* error;
  30. BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];
  31. if (!isSaveSuccess) {
  32. NSLog(@"Error:%@",error);
  33. }else{
  34. NSLog(@"Save successful!");
  35. }
  36. }
  37. //查询
  38. - (IBAction)query:(id)sender {
  39. NSFetchRequest* request=[[NSFetchRequest alloc] init];
  40. NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
  41. [request setEntity:user];
  42. //    NSSortDescriptor* sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
  43. //    NSArray* sortDescriptions=[[NSArray alloc] initWithObjects:sortDescriptor, nil];
  44. //    [request setSortDescriptors:sortDescriptions];
  45. //    [sortDescriptions release];
  46. //    [sortDescriptor release];
  47. NSError* error=nil;
  48. NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  49. if (mutableFetchResult==nil) {
  50. NSLog(@"Error:%@",error);
  51. }
  52. NSLog(@"The count of entry: %i",[mutableFetchResult count]);
  53. for (User* user in mutableFetchResult) {
  54. NSLog(@"name:%@----age:%@------sex:%@",user.name,user.age,user.sex);
  55. }
  56. [mutableFetchResult release];
  57. [request release];
  58. }
  59. //更新
  60. - (IBAction)update:(id)sender {
  61. NSFetchRequest* request=[[NSFetchRequest alloc] init];
  62. NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
  63. [request setEntity:user];
  64. //查询条件
  65. NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];
  66. [request setPredicate:predicate];
  67. NSError* error=nil;
  68. NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  69. if (mutableFetchResult==nil) {
  70. NSLog(@"Error:%@",error);
  71. }
  72. NSLog(@"The count of entry: %i",[mutableFetchResult count]);
  73. //更新age后要进行保存,否则没更新
  74. for (User* user in mutableFetchResult) {
  75. [user setAge:[NSNumber numberWithInt:12]];
  76. }
  77. [_myAppDelegate.managedObjectContext save:&error];
  78. [mutableFetchResult release];
  79. [request release];
  80. }
  81. //删除
  82. - (IBAction)del:(id)sender {
  83. NSFetchRequest* request=[[NSFetchRequest alloc] init];
  84. NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];
  85. [request setEntity:user];
  86. NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];
  87. [request setPredicate:predicate];
  88. NSError* error=nil;
  89. NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  90. if (mutableFetchResult==nil) {
  91. NSLog(@"Error:%@",error);
  92. }
  93. NSLog(@"The count of entry: %i",[mutableFetchResult count]);
  94. for (User* user in mutableFetchResult) {
  95. [_myAppDelegate.managedObjectContext deleteObject:user];
  96. }
  97. if ([_myAppDelegate.managedObjectContext save:&error]) {
  98. NSLog(@"Error:%@,%@",error,[error userInfo]);
  99. }
  100. }
  101. @end

对于多线程它是不安全的,需要进行特殊处理下次再说吧

时间: 2024-08-30 08:13:56

ios中的coredata的相关文章

ios中的coredata的使用

本文转载至 http://m.blog.csdn.net/blog/chen505358119/9334831 Core Data数据持久化是对SQLite的一个升级,它是ios集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类. (1)NSManagedObjectModel(被管理的对象模型) 相当于实体,不过它包含 了实体间的关系 (2)NSManagedObjectContext(被管理的对象上下文) 操作实际内容 作用:插入数据  查询  更新  删除 (3

IOS中CoreData浅析

CoreData简介: 什么是CoreData? Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象.在此数据操作期间,我们不需要编写任何SQL语句 CoreData 不能执行SQL语句 取而代之,操作的是对象.而常用的三方库 FMDB SQLite 可以直接SQL语句 CoreData和数据库有什么区别? CoreData是一个苹果原生的框架,它拥有像数

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

IOS学习:ios中的数据持久化初级(文件.xml.json.sqlite.CoreData) 分类: ios开发学习2013-05-30 10:03 2316人阅读 评论(2) 收藏 举报 iOSXMLJSONSQLiteCoreData 一.文件操作 1.因为应用是在沙盒(Sandbox)中的,在文件读写权限上受到限制,只能在几个目录下读写文件: * Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录 * tmp:存放临时文件,iTunes不会备份和恢复

iOS中几种数据持久化方案

概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) preference(偏好设置) NSKeyedArchiver(归档) SQLite 3 CoreData 沙盒 在介绍各种存储方法之前,有必要说明以下沙盒机制.iOS程序默认情况下只能访问程序自己的目录,这个目录被称为"沙盒". 1.结构 既然沙盒就是一个文件夹,那就看看里面有什么吧

iOS中的数据存储

SQLite3 SQLite3是一款开源的嵌入式关系型数据库,可移植性好,易使用,内存开销小. SQLite3是无类型的,意味着你可以保存任何类型的数据到任意表的任意字段中. SQLite3常用的4种数据类型:text(文本字符串), integer(整型值), real(浮点值), blob(二进制数据(比如文件)). 在iOS中使用SQLite3,首先要添加库文件'libsqlite3.dylib'和导入主头文件#import<sqlite3.h> SQL语句的特点: 1> 不区分大

iOS狂暴之路---iOS中应用的数据存储方式解析

一.前言 前面一篇文章中已经介绍了iOS应用中的视图控制器知识点,而本文不会按照常理来介绍View的知识点,而是先介绍iOS中的数据存储知识点,因为关于View的知识点太多了,后面会连续详细介绍一下.这篇先来看一下iOS中的数据存储功能分析.每一个iOS应用和Android应用一样,都有其对应的沙盒存储自己的数据,但是iOS和Android有一个区别就在于没有SD卡的概念了,也就说在iOS中应用的数据只能保存到自己的沙盒中.这也可以看出来iOS为了应用的安全考虑. 在开发Android的时候都知

iOS中几种数据持久化方案总结

概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) preference(偏好设置) NSKeyedArchiver(归档) SQLite 3 CoreData 沙盒 在介绍各种存储方法之前,有必要说明以下沙盒机制.iOS程序默认情况下只能访问程序自己的目录,这个目录被称为"沙盒". 1.结构 既然沙盒就是一个文件夹,那就看看里面有什么吧

iOS中一些 常用的第三方库

转自ibireme的博客 做iOS开发总会接触到一些第三方库,这里整理一下,做一些吐槽. 目前比较活跃的社区仍旧是Github,除此以外也有一些不错的库散落在Google Code.SourceForge等地方.由于Github社区太过主流,这里主要介绍一下Github里面流行的iOS库. 首先整理了一份Github上排名靠前的iOS库(大概600个repos) 除了逛一下每日/每月流行之外,也可以到这里来看一下整个iOS Repos的排名. 下面是一些比较流行的第三方库: HTTP 相比较之下

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

iOS中常用的四种数据持久化方法简介 iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults standardUserDefaults]就够用了 @interface User : NSObject <NSCoding>@property (nonatomic, assign) NSInteger userID;@property (nonatomic,