Core Data是ORM框架,很像.NET框架中的EntityFramework。使用的基本步骤是:

  • 在项目属性里引入CoreData.framework (标准库)
  • 在项目中新建DataModel (生成*.xcdatamodeld文件)
  • 在DataModel里创建Entity
  • 为Entity生成头文件(菜单Editor/Create NSMangedObject Subclass...)
  • 在项目唯一的委托类(AppDelegate.h, AppDelegate.m)里添加managedObjectContext 用来操作Core Data
  • 代码任意位置引用 managedObjectContext 读写数据

模型:(注意:myChapter, myContent这些关系都是Cascade,这样删父对象时才会删除子对象)

生成的头文件:

/* Book.h */
@interface Book : NSManagedObject @property (nonatomic, retain) NSNumber * bookId;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * author;
@property (nonatomic, retain) NSString * summary;
@property (nonatomic, retain) NSSet *myChapters;
@end @interface Book (CoreDataGeneratedAccessors) - (void)addMyChaptersObject:(NSManagedObject *)value;
- (void)removeMyChaptersObject:(NSManagedObject *)value;
- (void)addMyChapters:(NSSet *)values;
- (void)removeMyChapters:(NSSet *)values; @end /* Chapter.h */
@class Book;
@interface Chapter : NSManagedObject @property (nonatomic, retain) NSNumber * chapId;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * orderId;
@property (nonatomic, retain) Book *ownerBook;
@property (nonatomic, retain) NSManagedObject *myContent; @end /* TextContent.h */
@class Chapter; @interface TextContent : NSManagedObject @property (nonatomic, retain) NSNumber * chapId;
@property (nonatomic, retain) NSString * text;
@property (nonatomic, retain) Chapter *ownerChapter; @end

委托类代码


AppDelegate.h

// AppDelegate.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h> #import "Book.h"
#import "Chapter.h"
#import "TextContent.h" @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext; @end

AppDelegate.m

@implementation AppDelegate
@synthesize managedObjectContext = _managedObjectContext; -(NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
} _managedObjectContext = [[NSManagedObjectContext alloc]init]; // 设置数据库路径
NSURL *url = [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
NSURL *storeDataBaseURL = [url URLByAppendingPathComponent:@"BOOKS.sqlite"]; // 创建presistentStoreCoordinator
NSError *error = nil;
NSPersistentStoreCoordinator *presistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles: nil]]; // 指定存储类型和路径
if (![presistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeDataBaseURL options:nil error:&error]) {
NSLog(@"error : %@", error);
} [_managedObjectContext setPersistentStoreCoordinator: presistentStoreCoordinator];
return _managedObjectContext;
}

使用_managedObjectContext操作Core Data

// 保存新对象
-(void) testStore
{
// 从AppDelegate 获得context
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 第一个章节
TextContent *content1 = [NSEntityDescription insertNewObjectForEntityForName:@"TextContent" inManagedObjectContext:context];
content1.chapId = [NSNumber numberWithInt:];
content1.text = @"hello1"; Chapter *chapter1 = (Chapter *)[NSEntityDescription insertNewObjectForEntityForName:@"Chapter" inManagedObjectContext:context];
chapter1.name = @"hello1";
chapter1.orderId = [NSNumber numberWithInt:];
chapter1.chapId = [NSNumber numberWithInt:];
chapter1.myContent = content1; // 第二个章节
TextContent *content2 = [NSEntityDescription insertNewObjectForEntityForName:@"TextContent" inManagedObjectContext:context];
content2.chapId = [NSNumber numberWithInt:];
content2.text = @"hello2"; Chapter *chapter2 = (Chapter *)[NSEntityDescription insertNewObjectForEntityForName:@"Chapter" inManagedObjectContext:context];
chapter2.name = @"hello2";
chapter2.orderId = [NSNumber numberWithInt:];
chapter2.chapId = [NSNumber numberWithInt:];
chapter2.myContent = content2; // 书籍对象
Book *book = (Book *)[NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context];
book.bookId = [NSNumber numberWithInt:];
book.name = @"hello";
book.author = @"Kitty";
book.summary = @"test";
[book addMyChaptersObject:chapter1];
[book addMyChaptersObject:chapter2]; // 提交到持久存储
if ([context hasChanges]) {
[context save:nil];
}
} // 读取对象
-(void) testRead
{
// 从AppDelegate 获得context
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 生成查询对象 (查询全部数据)
NSEntityDescription *entityDescr = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescr]; // 执行查询
NSError *error;
NSArray *arrayBooks = [context executeFetchRequest:request error:&error]; // 定义排序方式 (根据集合中Chapter对象的orderId属性排序,升序)
NSSortDescriptor *chaptersDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"orderId" ascending:YES]; // 遍历结果集
for (Book *book in arrayBooks) { // 使用当前对象属性
NSLog(@"book name = %@", book.name); // 使用当前对象的集合属性,转成数组
NSArray *arrayChapters = [book.myChapters allObjects]; // 排序
arrayChapters = [arrayChapters
sortedArrayUsingDescriptors:[NSArray arrayWithObjects:chaptersDescriptor,nil]]; // 遍历子数组
for (Chapter *chapter in arrayChapters) {
NSLog(@"chapter name = %@", chapter.name); TextContent *content = (TextContent*) chapter.myContent;
NSLog(@"chapter text = %@", content.text);
}
}
} // 更新对象属性
-(void) testUpdate
{
// 从AppDelegate 获得context
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 生成Request对象
NSEntityDescription *entityDescr = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescr]; // 执行查询
NSError *error;
NSArray *array = [context executeFetchRequest:request error:&error]; // 更改对象属性
Book * book = array[];
book.name = @"BOOKS"; // 提交到持久存储
if ([context hasChanges]) {
[context save:nil];
}
} // 删除对象
-(void) testRemove
{
// 从AppDelegate 获得context
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext]; // 生成Request对象
NSEntityDescription *entityDescr = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescr]; // 执行查询
NSError *error;
NSArray *array = [context executeFetchRequest:request error:&error]; // 遍历删除对象,因为在模型里把关系设置为Cascade,所以子对象会被自动删除
for (Book *book in array) {
[context deleteObject:book];
} // 提交到持久存储
if ([context hasChanges]) {
[context save:nil];
}
}

iOS: Core Data入门的更多相关文章

  1. 《驾驭Core Data》 第二章 Core Data入门

    本文由海水的味道编译整理,请勿转载,请勿用于商业用途.    当前版本号:0.4.0 第二章 Core Data入门 本章将讲解Core Data框架中涉及的基本概念,以及一个简单的Core Data ...

  2. Core Data入门

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

  3. Core Data入门-备用

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

  4. iOS:Core Data 中的简单ORM

    我们首先在xcdatamodel文件中设计我们的数据库:例如我建立一个Data的实体,里面有一个String类型的属性name以及一个Integer类型的num: 然后选中Data,添加文件,选择NS ...

  5. Core Data 入门

    1. 基本概念 Core Data是一种被称为对象关系映射(Object-Relational Mapping,ORM)技术的实现. Core Data 架构图如下: 五个概念: (1)数据模型(Da ...

  6. iOS Core data多线程并发访问的问题

    大家都知道Core data本身并不是一个并发安全的架构:不过针对多线程访问带来的问题,Apple给出了很多指导:同时很多第三方的开发者也贡献了很多解决方法.不过最近碰到的一个问题很奇怪,觉得有一定的 ...

  7. IOS - CORE DATA的目录(xcode6)

       当使用coredata作为app的后台数据存储介质后,我们很想知道数据是否成功插入.为此,我想找到coredata.sqlite的文件 代码中指定的存储目录为: - (NSURL *)appli ...

  8. iOS Core Data 数据库的加密(待研究)

    https://github.com/project-imas/encrypted-core-data 使用起来很方便,底层还是使用了SQLCipher,有时间要研究一下! 数据库的密码不能用固定字符 ...

  9. 《驾驭Core Data》 第三章 数据建模

    本文由海水的味道编译整理,请勿转载,请勿用于商业用途.    当前版本号:0.1.2 第三章数据建模 Core Data栈配置好之后,接下来的工作就是设计对象图,在Core Data框架中,对象图被表 ...

随机推荐

  1. 使用C#WebClient类访问(上传/下载/删除/列出文件目录)由IIS搭建的http文件服务器

    前言 为什么要写这边博文呢?其实,就是使用C#WebClient类访问由IIS搭建的http文件服务器的问题花了我足足两天的时间,因此,有必要写下自己所学到的,同时,也能让广大的博友学习学习一下. 本 ...

  2. Android(java)学习笔记168:Java异常分类

    Java异常可分为3种: (1)编译时异常:Java.lang.Exception (2)运行期异常:Java.lang.RuntimeException (3)错误:Java.lang.Error

  3. MVC缓存,使用数据层缓存,添加或修改时让缓存失效

    在"MVC缓存01,运用控制器缓存或数据层缓存"中,在数据层中可以设置缓存的有用时刻.但这个还不够"智能",常常期望在修改或创立的时分使缓存失效,加载新的数据. ...

  4. Java实现微信菜单json字符串拼接

    Java实现微信菜单json字符串拼接 微信菜单拼接json字符串方法 >>>>>>>>>>>>>>>> ...

  5. javascript的面向对象编程

    面象对象编程技术的核心理念:封装.继承.多态:在一些主流的高级编程语言中,比如:C#,VB.NET,JAVA,PHP等都是很容易实现的,而如果要在javascript中实现面象对象编程,可就不那么直接 ...

  6. 无法加载协定为“ServiceReference1.ReportWsSoap”的终结点配置部分,因为找到了该协定的多个终结点配置。请按名称指示首选的终结点配置部分。

    前言 引用websevice时,有时会出现如下错误: 异常详细信息: System.InvalidOperationException: 无法加载协定为“ServiceReference1.Repor ...

  7. iOS中的几种定时器详解

    在软件开发过程中,我们常常需要在某个时间后执行某个方法,或者是按照某个周期一直执行某个方法.在这个时候,我们就需要用到定时器. 然而,在iOS中有很多方法完成以上的任务,经过查阅资料,大概有三种方法: ...

  8. PHP 学习笔记 (四)

    Wordpress 框架中的一些函数: wp_get_nav_menu($default): 根据条件$default 获取menu, 默认获取所有的menu 其中 $default 默认如下所示: ...

  9. storm简介[ZZ]

    场景 伴随着信息科技日新月异的发展,信息呈现出爆发式的膨胀,人们获取信息的途径也更加多样.更加便捷,同时对于信息的时效性要求也越来越高.举个搜索 场景中的例子,当一个卖家发布了一条宝贝信息时,他希望的 ...

  10. [Introduction to programming in Java 笔记] 1.3.9 Factoring integers 素因子分解

    素数 A prime is an integer greater than one whose only positive divisors are one and itself.整数的素因子分解是乘 ...