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

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

ios中的coredata的使用的更多相关文章

  1. ios中的coredata

    本文转载至 http://blog.csdn.net/chen505358119/article/details/9334831 分类: ios2013-07-15 18:12 12449人阅读 评论 ...

  2. IOS中CoreData浅析

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

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

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

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

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

  5. iOS在framework中使用CoreData出现崩溃问题及解决方法

    公司项目中有一个功能,保存授权令牌数据.最开始只有一条数据,所以就直接保存在了userdefaults中.后来需要两条数据,还是保存在userdefaults中,其中一条为固定的,另一条不固定可以进行 ...

  6. iOS基础教程:在建好的项目中加入CoreData[转]

    这几天在做一个ios的小项目,项目中需要对数据进行基本的增删改查操作.于是就想用一把CoreData.但在创建项目初期,没有包含进CoreData.于是就在已建好的项目中加入CoreData.由于第一 ...

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

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

  8. iOS 中有用的开源库

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

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

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

随机推荐

  1. 【WP8】为Webbrowser添加ScrollBar

    在WP8中,控件WebBrowser没有提供对滚动条的支持,而在内置的IE中,却可以显示出滚动条(微软这是在坑我们吗),但如果在客户端使用Webbrowser的话,自己构造ScrollBar来显示 通 ...

  2. SQLServer------备份与还原

    转载: http://www.cnblogs.com/zgqys1980/archive/2012/07/04/2576382.html

  3. SpringBoot------添加保存时自动编译插件

    .右键Java项目 .选择“Spring Tools” 3.选择“Add Boot DevTools” 4.每次使用Ctrl + S键时就会自动编译了 实际上是在Pom.xml文件中添加了如下Java ...

  4. 开源一个简易轻量的reactor网络框架

    github https://github.com/sea-boat/net-reactor net-reactor it's a simple and easy net framework with ...

  5. Git Step by Step – (4) 探索.git目录

    前面一篇文章介绍了Git对象模型,接下来我们就进入".git"目录看看到底有什么东西,目录中哪些东西又跟Git对象模型相关.结合这个目录,我们将进一步了解Git的工作原理. .gi ...

  6. nodejs服务器部署教程三

    安装mongodb数据库 如何在ubuntu上安装mongodb数据库,其实官方文档写的很清楚啦 sudo apt-key adv --keyserver hkp://keyserver.ubuntu ...

  7. wee hours

    前言: 程序员问科比:“你为什么这么成功? ” 科比:“你知道凌晨四点的城市是什么样子吗?” 程序员:“知道,一般那个时候我还在写代码,怎么了?” 科比:“没事了……” 说起程序员,可能很多人脑中会蹦 ...

  8. C++开发--在Visual Studio2013中使用boost::split()编译过程中出现error C4996

    Visual Studio is being overly cautious.  In debug mode, visual studio uses something called "Ch ...

  9. Java使用dom4j读取xml时报错:org.dom4j.DocumentException: Error on line 2 of document : Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence

    1.Java使用dom4j读取xml时报错: org.dom4j.DocumentException: Error on line 2 of document  : Invalid byte 2 of ...

  10. HTML 引用

    关于 HTML 引用: (1) <q> 和 <blockquote> 用于实现长短不一的引用语(2) <q> 用于短的引用,<blockquote> 用 ...