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
本文转载至 http://blog.csdn.net/chen505358119/article/details/9334831 分类: ios2013-07-15 18:12 12449人阅读 评论 ...
- IOS中CoreData浅析
CoreData简介: 什么是CoreData? Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中, ...
- IOS学习:ios中的数据持久化初级(文件、xml、json、sqlite、CoreData)
IOS学习:ios中的数据持久化初级(文件.xml.json.sqlite.CoreData) 分类: ios开发学习2013-05-30 10:03 2316人阅读 评论(2) 收藏 举报 iOSX ...
- QF——iOS中的数据库操作:SQLite数据库,第三方封装库FMDB,CoreData
SQLite数据库: SQLite是轻量级的数据库,适合应用在移动设备和小型设备上,它的优点是轻量,可移植性强.但它的缺点是它的API是用C写的,不是面向对象的.整体来说,操作起来比较麻烦.所以,一般 ...
- iOS在framework中使用CoreData出现崩溃问题及解决方法
公司项目中有一个功能,保存授权令牌数据.最开始只有一条数据,所以就直接保存在了userdefaults中.后来需要两条数据,还是保存在userdefaults中,其中一条为固定的,另一条不固定可以进行 ...
- iOS基础教程:在建好的项目中加入CoreData[转]
这几天在做一个ios的小项目,项目中需要对数据进行基本的增删改查操作.于是就想用一把CoreData.但在创建项目初期,没有包含进CoreData.于是就在已建好的项目中加入CoreData.由于第一 ...
- iOS中的数据持久化方式
iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data. 1.属性列表 涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults ...
- iOS 中有用的开源库
youtube下载神器:https://github.com/rg3/youtube-dl vim插件:https://github.com/Valloric/YouCompleteMe vim插件配 ...
- iOS中常用的四种数据持久化技术
iOS中的数据持久化方式,基本上有以下四种:属性列表 对象归档 SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 [NSUserDefaults st ...
随机推荐
- MVC Controller向View传递数据
ASP.NET MVC中,Controller向View传递数据的方式有一下6种 ViewData ViewBag PartialView TempData ViewModel Tuple 1.Vie ...
- ubuntu-16.04.2-desktop-amd64.iso:安装Oracle11gR2
特点: 使用ubuntu-16.04.2-desktop-amd64.iso 不降级默认的gcc版本,(liveCD 自带默认为 gcc 5.4):仅需要建立“gcc -Wl,--no-as-need ...
- linux环境中,如何使用tar来创建压缩包?解压缩?
需求说明: 今天需要将一个tomcat目录打成压缩包,使用zip感觉有点慢,所以就想用tar来试试,之前一直使用tar的解压缩命令, 今天试试tar的压缩命令 操作过程: 1.通过tar的zcf选项进 ...
- 5种实现垂直居中css
摘要: 在我们制作页面的时候经常会遇到内容垂直居中的需求,今天分享5种垂直居中的方法,每种方法都有自己的优缺点,可以选择自己喜欢的方式.以下代码都经过本人亲自测试. line-height: < ...
- Hash冲突的解决方法
虽然我们不希望发生冲突,但实际上发生冲突的可能性仍是存在的.当关键字值域远大于哈希表的长度,而且事先并不知道关键字的具体取值时.冲突就难免会发 生.另外,当关键字的实际取值大于哈希表的长度时,而且表中 ...
- Java适配器模式的简单应用
对于刚从工厂生产出来的商品,有些功能并不能完全满足用户的需要.因此,用户通常会对其进行一定的改装工作.编写程序为普通的汽车增加GPS定位功能,借此演示适配器模式的用法. 思路分析: 这个问题的需求是, ...
- 8 -- 深入使用Spring -- 7... Spring 整合 Struts 2
8.7 Spring 整合 Struts2 8.7.1 启动Spring 容器 8.7.2 MVC框架与Spring整合的思考 8.7.3 让Spring管理控制器 8.7.4 使用自动装配
- javascript拖拽操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- C 修改命令行文本颜色
#include <Windows.h> #include <stdio.h> int main() { HANDLE h = GetStdHandle(STD_OUTPUT_ ...
- Nginx(六)-- 配置文件之Gzip
1.概念及作用 Gizp主要对内容.静态文件做压缩,用来提升网站访问速度,节省带宽. 2.使用方法 gzip既可以配置在server中,也可以配置在server外,此处配置在server中,如下: ...