CoreData是苹果官方推出的一种方便的面向对象的存储方式,相信大家都已经对其有所了解,但是对于CoreData的概念大家都存在部分的误区.给大家推荐个网址是苹果的官方文档的翻译版(http://objccn.io/issue-4-1/)这里详细的解释了CoreData存在以及出现的意义.下面我就带大家来学习下如何使用CoreData.

今天我们先学习最基础的CoreData的操作(单表操作)

第一步 创建一个带有CoreData的工程.

创建完成带有CoreData的工程后我们可以看到我们工程左边列表里有一个名字叫做CoreDataTest.xcdatamodeld的文件在哪里就是我们创建我们Model类实体文件的地方.

然后我们打开我们看到的那个文件,在里面我们创建一个叫做ClassEntity的实体名称.

在我们创建完成那个实体文件以后我们看到我们的中间列表里面有一个添加实体属性的位置.在这里我们添加三条属性.名字分别为name sex age 类型全部选择是string

在属性添加完成后我们就可以去生成对应的实体类文件我们需要先选中CoreDataTest.xcdatamodeld这个文件然后选择菜单栏上的Editor选择Creat NSManagerObject Subclass...

创建完成后我们可以看到两个叫做ClassEntity的文件被创建好了,然后我们再来看下其他不同于以往工程的地方.我们先来打开看下我们的AppDelegate.h文件,我们可以看到在AppDelegate.h文件中和以前我们创建的工程不同的地方.

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; //被管理者对象上下文
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; //数据模型器管理类
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; //数据连接器工具类 (连接助理)
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; //通过对上下文的保存,将上下文管理的对象保存到实体数据库.
- (void)saveContext; //获取数据库所在的路径
- (NSURL *)applicationDocumentsDirectory; @end

看完AppDelegate.h中的不同后我们来看下AppDelegate.m中有什么不同.

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; - (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou.LessonCoreData" in the application's documents directory.
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]); return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
} - (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
} //momd 去查询xcdatamodeld
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"LessonCoreData" withExtension:@"momd"];
//创建数据器模型工具类.
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
} - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
} // Create the coordinator and store //使用数据模型器工具类实例化数据连接器工具类.
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
//数据库的绝对路径.
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LessonCoreData.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data."; //创建数据库的过程.
//1.数据持久化类型
//2.设置信息
//3.数据库的绝对路径.
//4.配置SQL数据的选项
//5.错误信息的赋值.
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this 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();
} return _persistentStoreCoordinator;
} - (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
} //通过GET方法创建数据连接器工具类
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
//判断数据器连接工具类是否为空
if (!coordinator) {
return nil;
}
//创建数据管理器工具类
_managedObjectContext = [[NSManagedObjectContext alloc] init];
//设置数据管理器工具类的数据连接器.
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
} #pragma mark - Core Data Saving support
//保存你当前的操作到数据库中.
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = 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();
}
}
}

这些就是我们在创建完成一个带有CoreData的工程和以前我们创建的工程的区别.然后我们来看下我们当前应该如何对我们当前创建的数据库来操作.首先进入到我们当前需要用到CoreData的类文件中创建AppDelegate的实例,然后再当前类的- (void)viewWillDidLoad方法中去实现对CoreData的操作.

#import "ViewController.h"
#import "AppDelegate.h"
#import "ClassEntity.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
//获取当前的AppDelegate的实例.
AppDelegate *appdelegate = [UIApplication sharedApplication].delegate; ////为数据库中增加数据 //创建当前实体类的实体描述
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ClassEntity" inManagedObjectContext:appdelegate.managedObjectContext]; //通过实体描述文件来创建当前类的实例.
ClassEntity *classEntity = [[ClassEntity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:appdelegate.managedObjectContext]; //为实例的属性赋值.
classEntity.name = @"张三";
classEntity.sex = @"男";
classEntity.age = @"21"; //保存操作到真实的数据库内.
[appdelegate saveContext]; ////查询数据库内存放的实体内容. //创建查询语句
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"ClassEntity"]; //通过AppDelegate来查询你想要的数据库.
//注意返回值为数组.
NSArray *arr = [appdelegate.managedObjectContext executeFetchRequest:request error:nil]; //打印数组
NSLog(@"%@",arr); ////删除数据库中存放的实体. //通过查询获取到你需要删除的表单中的所有内容. //通过返回值获取到的数组来查找你当前想要的实体位置.
ClassEntity *classEntity1 = [arr objectAtIndex:0]; //通过AppDelegate
[appdelegate.managedObjectContext deleteObject:classEntity1]; //通过AppDelegate来保存到你的真实数据库中.
[appdelegate saveContext]; // Do any additional setup after loading the view, typically from a nib.
}

这些就是本次的CoreData是如何使用的.这次的内容也就到这里结束了.下次会和大家分享多表的CoreData的操作.最后附上我的文件列表截图

.

关于CoreData的理解和使用.的更多相关文章

  1. coreData 深入理解4 --总结 (线程安全与同步--iOS5 前后对比)

    Core Data是iOS中很重要的一个部分,可以理解为基于SQLite(当然也可以是其他的Storage,如In-memory,只是SQLite比较常见)的一个ORM实现,所以有关系数据库的特性,又 ...

  2. iOS -数据持久化方式-以真实项目讲解

    前面已经讲解了SQLite,FMDB以及CoreData的基本操作和代码讲解(CoreData也在不断学习中,上篇博客也会不断更新中).本篇我们将讲述在实际开发中,所使用的iOS数据持久化的方式以及怎 ...

  3. 初识CoreData与详解

    Core Data数据持久化是对SQLite的一个升级,它是iOS集成的,在说Core Data之前,我们先说说在CoreData中使用的几个类. (1)NSManagedObjectModel(被管 ...

  4. CoreData教程

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

  5. iOS开发之表视图爱上CoreData

    在接触到CoreData时,感觉就是苹果封装的一个ORM.CoreData负责在Model的实体和sqllite建立关联,数据模型的实体类就相当于Java中的JavaBean, 而CoreData的功 ...

  6. iOS - CoreData 数据库存储

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

  7. IOS中CoreData浅析

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

  8. iOS-数据持久化-CoreData

    CoreData详解 介绍: 在Cocoa环境下,如果你想使用数据库(如sqlite),你可以使用sql语句的方式通过相关的工具类进行数据库的直接操作.当然你也可以通过别人封装之后的一些简单框架,使得 ...

  9. CoreData的使用

    #import "ViewController.h" #import "Person.h" @interface ViewController () <U ...

随机推荐

  1. Oleg Sych - » Pros and Cons of T4 in Visual Studio 2008

    Oleg Sych - » Pros and Cons of T4 in Visual Studio 2008 Pros and Cons of T4 in Visual Studio 2008 Po ...

  2. Skulpt

    Skulpt Python. Client side. Skulpt is an entirely in-browser implementation of Python. No preprocess ...

  3. telnet 命令使用详解

    1..关于NTLM验证由于Telnet功能太强大,而且也是入侵者使用最频繁的登录手段之一,因此微软公司为Telnet添加了身份验证,称为NTLM验证,它要求Telnet终端除了需要有Telnet服务主 ...

  4. 安装vs2015的时候出现的各种 1402错误

    经搜索与尝试,确认为注册表权限问题,改过好几个子项,均提示不能修改设置子项的所有者什么的,后来一怒之下,直接把install节点下的compom项的权限的administratos权限删掉,删除的时候 ...

  5. Struts2(一)——总体介绍

    这篇博客开始将总结一下有关框架的知识,在开发中合适的利用框架会使我们的开发效率大大提高.当今比较流行的开源框架: 关注数据流程的MVC框架 (Struts1/2, WebWork, Spring MV ...

  6. Change the ball(找规律)

    Change the ball Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  7. Red and Black(简单dfs)

    Red and Black Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  8. RMAN数据库恢复之恢复归档日志文件

    恢复归档日志文件如果只是为了在恢复数据文件之后应用归档文件,那并不需要手动对归档文件进行恢复,RMAN会在RECOVER时自动对适当的归档进行恢复.单独恢复归档文件一般是有特别的需求,如创建了Data ...

  9. CSS3实现图片鼠标悬浮放大效果

    .excerpt .focus a img{ -webkit-transition: all ease .3s; transition: all ease .3s }.excerpt .focus a ...

  10. trangleProble switch方法 java

    public class trangleProblem { static int res=1; int codePart=1; int n=100; Stack<Param> stack= ...