第一次真正的使用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

  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
  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
  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;
  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

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

 

(五)CoreData 使用 (转)的更多相关文章

  1. CoreData的介绍和使用

    一.CoreData是什么? CoreData是iOS SDK里的一个很强大的框架,允许程序员以面向对象的方式存储和管理数据.使用CoreData框架,程序员可以轻松有效地通过面向对象的接口管理数据 ...

  2. iOS原生数据存储策略

    一 @interface NSCache : NSObject Description A mutable collection you use to temporarily store transi ...

  3. CoreData 从入门到精通(五)CoreData 和 TableView 结合

    我们知道 CoreData 里存储的是具有相同结构的一系列数据的集合,TableView 正好是用列表来展示一系列具有相同结构的数据集合的.所以,要是 CoreData 和 TableView 能结合 ...

  4. 数据持久化(五)之CoreData

    @简单的说,Core Data就是能够存储到磁盘的对象图,[...]Core Data能够帮我们做非常多任务作.它能够作为软件的整个模型层. 它不只在磁盘上存储数据.也把我们须要的数据对象读取到内存中 ...

  5. iOS基本数据库存储方式 - CoreData

    CoreData 创建模型文件的过程 1.选择模板 2.添加实体 3.添加实体的属性[注意]属性的首字母必须小写 一.CoreData管理类(必备以下三个类对象) 1.CoreData数据操作的上下文 ...

  6. CoreData教程

    网上关于CoreData的教程能搜到不少,但很多都是点到即止,真正实用的部分都没有讲到,而基本不需要的地方又讲了太多,所以我打算根据我的使用情况写这么一篇实用教程.内容将包括:创建entity.创建r ...

  7. CoreData总结

    Core Data,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象.在此数据操作期间,我们不需要编写任何 ...

  8. iOS五种本地缓存数据方式

    iOS五种本地缓存数据方式   iOS本地缓存数据方式有五种:前言 1.直接写文件方式:可以存储的对象有NSString.NSArray.NSDictionary.NSData.NSNumber,数据 ...

  9. iOS CoreData技术学习资源汇总

    一.CoreData学习指引 1. 苹果官方:Core Data Programming Guide 什么是CoreData? 创建托管对象模型 初始化Core Data堆栈 提取对象 创建和修改自定 ...

随机推荐

  1. Machine Learning - 第7周(Support Vector Machines)

    SVMs are considered by many to be the most powerful 'black box' learning algorithm, and by posing构建 ...

  2. 串行通讯之Qt

    目录 第1章 Qt 串行通讯    1 1.1 配置.pro文件    1 1.2 查询串口信息    1 1.3 配置.打开串口    3 1.4 setRequestToSend在Windows上 ...

  3. java 集合(Map3)

    Map接口下的实现类: HashMap 1.存储原理: 向HashMap中添加元素时,首先会调用hashCode(),算的哈希值,然后 算出该元素在哈希表中的存储位置. 情况1 情况2(java  集 ...

  4. window2012 64bit 安装sqlserver2012 64bit调用excel的驱动安装

    如果电脑已经安装了32bit的office那么可以使用 管理员权限打开cmd,然会执行以下命令 AccessDatabaseEngine_X64.exe /passive

  5. VS2012更改项目编译后文件输出目录

    1.现在我的解决方案里有存在两个项目,分别是类库项目ClassLibrary1和控制台项目ConsoleApplication1,默认情况下当解决方案重新生成后,这两个项目所对应的编译后文件分别会存在 ...

  6. [Hadoop 周边] Hadoop资料收集【转】

    原文网址: http://www.iteblog.com/archives/851 最直接的学习参考网站当然是官网啦: http://hadoop.apache.org/ Hadoop http:// ...

  7. python 第三方模块 转 https://github.com/masterpy/zwpy_lst

    Chardet,字符编码探测器,可以自动检测文本.网页.xml的编码. colorama,主要用来给文本添加各种颜色,并且非常简单易用. Prettytable,主要用于在终端或浏览器端构建格式化的输 ...

  8. JavaScript中给对象添加函数的方式

    1. function 类名(){ this.属性: } var 对象名=new 类名(): function 函数名(){ //执行代码 } 对象名.属性名=函数名: 对象名.属性名(): func ...

  9. Servlet后续的尾(yi)巴--------Filter过滤器

    -------载录自  http://www.blogjava.net/yangaiyou/archive/2007/08/29/140854.html  感谢博主心如止水 一心向佛 描写出这么的具体 ...

  10. 130. Surrounded Regions -- 被某字符包围的区域

    Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured ...