深入浅出 Cocoa 之 Core Data(2)- 代码示例

CC 许可,转载请注明出处

前面详细讲解了 Core Data 的框架以及设计的类,下面我们来讲解一个完全手动编写代码使用这些类的示例,这个例子来自苹果官方示例。在这个例子里面,我们打算做这样一件事情:记录程序运行记录(时间与 process id),并保存到xml文件中。我们使用 Core Data 来做这个事情。

示例代码下载:点击这里

一,建立一个新的 Mac command-line tool application 工程,命名为 CoreDataTutorial。为支持垃圾主动回收机制,点击项目名称,在右边的 Build Setting 中查找 garbage 关键字,将找到的 Objective-C Garbage Collection 设置为 Required [-fobj-gc-only]。并将  main.m 中 的 main() 方法修改为如下:

  1. int main (int argc, const char * argv[])
  2. {
  3. NSLog(@" === Core Data Tutorial ===");
  4. // Enable GC
  5. //
  6. objc_startCollectorThread();
  7. return 0;
  8. }

二,创建并设置模型类

在 main() 之前添加如下方法:

  1. NSManagedObjectModel *managedObjectModel()
  2. {
  3. static NSManagedObjectModel *moModel = nil;
  4. if (moModel != nil) {
  5. return moModel;
  6. }
  7. moModel = [[NSManagedObjectModel alloc] init];
  8. // Create the entity
  9. //
  10. NSEntityDescription *runEntity = [[NSEntityDescription alloc] init];
  11. [runEntity setName:@"Run"];
  12. [runEntity setManagedObjectClassName:@"Run"];
  13. [moModel setEntities:[NSArray arrayWithObject:runEntity]];
  14. // Add the Attributes
  15. //
  16. NSAttributeDescription *dateAttribute = [[NSAttributeDescription alloc] init];
  17. [dateAttribute setName:@"date"];
  18. [dateAttribute setAttributeType:NSDateAttributeType];
  19. [dateAttribute setOptional:NO];
  20. NSAttributeDescription *idAttribute = [[NSAttributeDescription alloc] init];
  21. [idAttribute setName:@"processID"];
  22. [idAttribute setAttributeType:NSInteger32AttributeType];
  23. [idAttribute setOptional:NO];
  24. [idAttribute setDefaultValue:[NSNumber numberWithInteger:-1]];
  25. // Create the validation predicate for the process ID.
  26. // The following code is equivalent to validationPredicate = [NSPredicate predicateWithFormat:@"SELF > 0"]
  27. //
  28. NSExpression *lhs = [NSExpression expressionForEvaluatedObject];
  29. NSExpression *rhs = [NSExpression expressionForConstantValue:[NSNumber numberWithInteger:0]];
  30. NSPredicate *validationPredicate = [NSComparisonPredicate
  31. predicateWithLeftExpression:lhs
  32. rightExpression:rhs
  33. modifier:NSDirectPredicateModifier
  34. type:NSGreaterThanPredicateOperatorType
  35. options:0];
  36. NSString *validationWarning = @"Process ID < 1";
  37. [idAttribute setValidationPredicates:[NSArray arrayWithObject:validationPredicate]
  38. withValidationWarnings:[NSArray arrayWithObject:validationWarning]];
  39. // set the properties for the entity.
  40. //
  41. NSArray *properties = [NSArray arrayWithObjects: dateAttribute, idAttribute, nil];
  42. [runEntity setProperties:properties];
  43. // Add a Localization Dictionary
  44. //
  45. NSMutableDictionary *localizationDictionary = [NSMutableDictionary dictionary];
  46. [localizationDictionary setObject:@"Date" forKey:@"Property/date/Entity/Run"];
  47. [localizationDictionary setObject:@"Process ID" forKey:@"Property/processID/Entity/Run"];
  48. [localizationDictionary setObject:@"Process ID must not be less than 1" forKey:@"ErrorString/Process ID < 1"];
  49. [moModel setLocalizationDictionary:localizationDictionary];
  50. return moModel;
  51. }

在上面的代码中:

1)我们创建了一个全局模型 moModel;
2)并在其中创建一个名为 Run 的 Entity,这个 Entity 对应的 ManagedObject 类名为 Run(很快我们将创建这样一个类);
3)给 Run Entity 添加了两个必须的 Property:date 和 processID,分别表示运行时间以及进程 ID;并设置默认的进程 ID 为 -1;
4)给 processID 特性设置检验条件:必须大于 0;
5)给模型设置本地化描述词典;

本地化描述提供对 Entity,Property,Error信息等的便于理解的描述,其可用的键值对如下表:

Key

Value

 

"Entity/NonLocalizedEntityName"

"LocalizedEntityName"

"Property/NonLocalizedPropertyName/Entity/EntityName"

"LocalizedPropertyName"

"Property/NonLocalizedPropertyName"

"LocalizedPropertyName"

"ErrorString/NonLocalizedErrorString"

"LocalizedErrorString"

三,创建并设置运行时类和对象

由于要用到存储功能,所以我们必须定义持久化数据的存储路径。我们在 main() 之前添加如下方法设置存储路径:

  1. NSURL *applicationLogDirectory()
  2. {
  3. NSString *LOG_DIRECTORY = @"CoreDataTutorial";
  4. static NSURL *ald = nil;
  5. if (ald == nil)
  6. {
  7. NSFileManager *fileManager = [[NSFileManager alloc] init];
  8. NSError *error = nil;
  9. NSURL *libraryURL = [fileManager URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask
  10. appropriateForURL:nil create:YES error:&error];
  11. if (libraryURL == nil) {
  12. NSLog(@"Could not access Library directory\n%@", [error localizedDescription]);
  13. }
  14. else
  15. {
  16. ald = [libraryURL URLByAppendingPathComponent:@"Logs"];
  17. ald = [ald URLByAppendingPathComponent:LOG_DIRECTORY];
  18. NSLog(@" >> log path %@", [ald path]);
  19. NSDictionary *properties = [ald resourceValuesForKeys:[NSArray arrayWithObject:NSURLIsDirectoryKey] error:&error];
  20. if (properties == nil)
  21. {
  22. if (![fileManager createDirectoryAtPath:[ald path] withIntermediateDirectories:YES attributes:nil error:&error])
  23. {
  24. NSLog(@"Could not create directory %@\n%@",
  25. [ald path], [error localizedDescription]);
  26. ald = nil;
  27. }
  28. }
  29. }
  30. }
  31. return ald;
  32. }

在上面的代码中,我们将持久化数据文件保存到路径:/Users/kesalin/Library/Logs/CoreDataTutorial 下。

下面,我们来创建运行时对象:ManagedObjectContext 和 PersistentStoreCoordinator。

  1. NSManagedObjectContext *managedObjectContext()
  2. {
  3. static NSManagedObjectContext *moContext = nil;
  4. if (moContext != nil) {
  5. return moContext;
  6. }
  7. moContext = [[NSManagedObjectContext alloc] init];
  8. // Create a persistent store coordinator, then set the coordinator for the context.
  9. //
  10. NSManagedObjectModel *moModel = managedObjectModel();
  11. NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:moModel];
  12. [moContext setPersistentStoreCoordinator: coordinator];
  13. // Create a new persistent store of the appropriate type.
  14. //
  15. NSString *STORE_TYPE = NSXMLStoreType;
  16. NSString *STORE_FILENAME = @"CoreDataTutorial.xml";
  17. NSError *error = nil;
  18. NSURL *url = [applicationLogDirectory() URLByAppendingPathComponent:STORE_FILENAME];
  19. NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE
  20. configuration:nil
  21. URL:url
  22. options:nil
  23. error:&error];
  24. if (newStore == nil) {
  25. NSLog(@"Store Configuration Failure\n%@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
  26. }
  27. return moContext;
  28. }

在上面的代码中:
1)我们创建了一个全局 ManagedObjectContext 对象 moContext;
2)并在设置其 persistent store coordinator,存储类型为 xml,保存文件名为:CoreDataTutorial.xml,并将其放到前面定义的存储路径下。

好,至此万事具备,只欠 ManagedObject 了!下面我们就来定义这个数据对象类。向工程添加 Core Data->NSManagedObject subclass 的类,名为 Run (模型中 Entity 定义的类名) 。

Run.h

  1. #import <CoreData/NSManagedObject.h>
  2. @interface Run : NSManagedObject
  3. {
  4. NSInteger processID;
  5. }
  6. @property (retain) NSDate *date;
  7. @property (retain) NSDate *primitiveDate;
  8. @property NSInteger processID;
  9. @end

Run.m

  1. //
  2. //  Run.m
  3. //  CoreDataTutorial
  4. //
  5. //  Created by kesalin on 8/29/11.
  6. //  Copyright 2011 kesalin@gmail.com. All rights reserved.
  7. //
  8. #import "Run.h"
  9. @implementation Run
  10. @dynamic date;
  11. @dynamic primitiveDate;
  12. - (void) awakeFromInsert
  13. {
  14. [super awakeFromInsert];
  15. self.primitiveDate = [NSDate date];
  16. }
  17. #pragma mark -
  18. #pragma mark Getter and setter
  19. - (NSInteger)processID
  20. {
  21. [self willAccessValueForKey:@"processID"];
  22. NSInteger pid = processID;
  23. [self didAccessValueForKey:@"processID"];
  24. return pid;
  25. }
  26. - (void)setProcessID:(NSInteger)newProcessID
  27. {
  28. [self willChangeValueForKey:@"processID"];
  29. processID = newProcessID;
  30. [self didChangeValueForKey:@"processID"];
  31. }
  32. // Implement a setNilValueForKey: method. If the key is “processID” then set processID to 0.
  33. //
  34. - (void)setNilValueForKey:(NSString *)key {
  35. if ([key isEqualToString:@"processID"]) {
  36. self.processID = 0;
  37. }
  38. else {
  39. [super setNilValueForKey:key];
  40. }
  41. }
  42. @end

注意:
1)这个类中的 date 和 primitiveDate 的访问属性为 @dynamic,这表明在运行期会动态生成对应的 setter 和 getter;
2)在这里我们演示了如何正确地手动实现 processID 的 setter 和 getter:为了让 ManagedObjecContext  能够检测 processID的变化,以及自动支持 undo/redo,我们需要在访问和更改数据对象时告之系统,will/didAccessValueForKey 以及 will/didChangeValueForKey 就是起这个作用的。
3)当我们设置 nil 给数据对象 processID 时,我们可以在 setNilValueForKey 捕获这个情况,并将 processID  置 0;
4)当数据对象被插入到 ManagedObjectContext 时,我们在 awakeFromInsert 将时间设置为当前时间。

三,创建或读取数据对象,设置其值,保存
好,至此真正的万事具备,我们可以创建或从持久化文件中读取数据对象,设置其值,并将其保存到持久化文件中。本例中持久化文件为 xml 文件。修改 main() 中代码如下:

  1. int main (int argc, const char * argv[])
  2. {
  3. NSLog(@" === Core Data Tutorial ===");
  4. // Enable GC
  5. //
  6. objc_startCollectorThread();
  7. NSError *error = nil;
  8. NSManagedObjectModel *moModel = managedObjectModel();
  9. NSLog(@"The managed object model is defined as follows:\n%@", moModel);
  10. if (applicationLogDirectory() == nil) {
  11. exit(1);
  12. }
  13. NSManagedObjectContext *moContext = managedObjectContext();
  14. // Create an Instance of the Run Entity
  15. //
  16. NSEntityDescription *runEntity = [[moModel entitiesByName] objectForKey:@"Run"];
  17. Run *run = [[Run alloc] initWithEntity:runEntity insertIntoManagedObjectContext:moContext];
  18. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  19. run.processID = [processInfo processIdentifier];
  20. if (![moContext save: &error]) {
  21. NSLog(@"Error while saving\n%@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
  22. exit(1);
  23. }
  24. // Fetching Run Objects
  25. //
  26. NSFetchRequest *request = [[NSFetchRequest alloc] init];
  27. [request setEntity:runEntity];
  28. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
  29. [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
  30. error = nil;
  31. NSArray *array = [moContext executeFetchRequest:request error:&error];
  32. if ((error != nil) || (array == nil))
  33. {
  34. NSLog(@"Error while fetching\n%@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
  35. exit(1);
  36. }
  37. // Display the Results
  38. //
  39. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  40. [formatter setDateStyle:NSDateFormatterMediumStyle];
  41. [formatter setTimeStyle:NSDateFormatterMediumStyle];
  42. NSLog(@"%@ run history:", [processInfo processName]);
  43. for (run in array)
  44. {
  45. NSLog(@"On %@ as process ID %ld", [formatter stringForObjectValue:run.date], run.processID);
  46. }
  47. return 0;
  48. }

在上面的代码中:
1)我们先获得全局的 NSManagedObjectModel 和 NSManagedObjectContext 对象:moModel 和 moContext;
2)并创建一个Run Entity,设置其 Property processID 为当前进程的 ID;
3)将该数据对象保存到持久化文件中:[moContext save: &error]。我们无需与 PersistentStoreCoordinator 打交道,只需要给 ManagedObjectContext 发送 save 消息即可,NSManagedObjectContext 会透明地在后面处理对持久化数据文件的读写;
4)然后我们创建一个 FetchRequest 来查询持久化数据文件中保存的数据记录,并将结果按照日期升序排列。查询操作也是由 ManagedObjectContext 来处理的:[moContext executeFetchRequest:request error:&error];
5)将查询结果打印输出;

大功告成!编译运行,我们可以得到如下显示:

  1. 2011-09-03 21:42:47.556 CoreDataTutorial[992:903] CoreDataTutorial run history:
  2. 2011-09-03 21:42:47.557 CoreDataTutorial[992:903] On 2011-9-3 下午09:41:56 as process ID 940
  3. 2011-09-03 21:42:47.557 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:16 as process ID 955
  4. 2011-09-03 21:42:47.558 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:20 as process ID 965
  5. 2011-09-03 21:42:47.558 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:24 as process ID 978
  6. 2011-09-03 21:42:47.559 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:47 as process ID 992

通过这个例子,我们可以更好理解 Core Data  的运作机制。在 Core Data 中我们最常用的就是 ManagedObjectContext,它几乎参与对数据对象的所有操作,包括对 undo/redo 的支持;而 Entity 对应的运行时类为 ManagedObject,我们可以理解为抽象数据结构 Entity 在内存中由 ManagedObject 来体现,而 Perproty 数据类型在内存中则由 ManagedObject 类的成员属性来体现。一般我们不需要与 PersistentStoreCoordinator 打交道,对数据文件的读写操作都由 ManagedObjectContext 为我们代劳了。

深入浅出 Cocoa 之 Core Data(2)- 手动编写代码的更多相关文章

  1. 深入浅出 Cocoa 之 Core Data(4)- 使用绑定

    深入浅出 Cocoa 之 Core Data(4)- 使用绑定 罗朝辉(http://blog.csdn.net/kesalin) CC 许可,转载请注明出处 前面讲解了 Core Data 的框架, ...

  2. 深入浅出 Cocoa 之 Core Data(3)- 使用绑定

    深入浅出 Cocoa 之 Core Data(3)- 使用绑定 罗朝辉(http://blog.csdn.net/kesalin) CC 许可,转载请注明出处 前面讲解了 Core Data 的框架, ...

  3. 深入浅出 Cocoa 之 Core Data(1)- 框架详解

    深入浅出 Cocoa 之 Core Data(1)- 框架详解 罗朝辉(http://blog.csdn.net/kesalin) CC 许可,转载请注明出处 Core data 是 Cocoa 中处 ...

  4. [Cocoa]深入浅出 Cocoa 之 Core Data(1)- 框架详解

    Core data 是 Cocoa 中处理数据,绑定数据的关键特性,其重要性不言而喻,但也比较复杂.Core Data 相关的类比较多,初学者往往不太容易弄懂.计划用三个教程来讲解这一部分: 框架详解 ...

  5. Cocoa 之 Core Data(2)- 代码示例

    前面详 细讲解了 Core Data 的框架以及设计的类,下面我们来讲解一个完全手动编写代码 使用这些类的示例,这个例子来自 苹果官方示例.在这个例子里面,我们打算做这样一件事 情:记录程序运行记录( ...

  6. 手把手教你从Core Data迁移到Realm

    来源:一缕殇流化隐半边冰霜 (@halfrost ) 链接:http://www.jianshu.com/p/d79b2b1bfa72 前言 看了这篇文章的标题,也许有些人还不知道Realm是什么,那 ...

  7. 手把手教你从 Core Data 迁移到 Realm

    前言 看了这篇文章的标题,也许有些人还不知道Realm是什么,那么我先简单介绍一下这个新生的数据库.号称是用来替代SQLite 和 Core Data的.Realm有以下优点: 使用方便 Realm并 ...

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

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

  9. Core Data & MagicalRecord

    iOS 本地数据持久化存储: 1.plist 2.归档 3.NSUserDefaults 4.NSFileManager 5.数据库 一.CoreData概述 CoreData是苹果自带的管理数据库的 ...

随机推荐

  1. 【Luogu P1637】 三元上升子序列

    对于每个数$a_i$,易得它对答案的贡献为 它左边比它小的数的个数$\times$它右边比它大的数的个数. 可以离散化后再处理也可以使用动态开点的线段树. 我使用了动态开点的线段树,只有需要用到这个节 ...

  2. git+jenkins持续集成一:git上传代码

    先注册一个账号,注册地址:https://github.com/ 记住地址 下载git本地客户端,下载地址:https://git-scm.com/download/win 一路next傻瓜安装,加入 ...

  3. mybatis maven 代码生成器(mysql)

    pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  4. Struts2 改变语言状态

    只要在请求中增加 request_locale=en_US 参数,就可以实现语言的切换,内部由拦截器实现

  5. 现代互联网的TCP拥塞控制(CC)算法评谈

    动机 写这篇文章本质上的动机是因为前天发了一个朋友圈,见最后的写在最后,但实际上,我早就想总结总结TCP拥塞控制算法点点滴滴了,上周总结了一张图,这周接着那些,写点文字. 前些天,Linux中国微信公 ...

  6. BZOJ2806 [Ctsc2012]Cheat 【后缀自动机 + 二分 + 单调队列优化DP】

    题目 输入格式 第一行两个整数N,M表示待检查的作文数量,和小强的标准作文库 的行数 接下来M行的01串,表示标准作文库 接下来N行的01串,表示N篇作文 输出格式 N行,每行一个整数,表示这篇作文的 ...

  7. Java面试题之在多线程情况下,单例模式中懒汉和饿汉会有什么问题呢?

    懒汉模式和饿汉模式: public class Demo { //private static Single single = new Single();//饿汉模式 private static S ...

  8. javaScript 笔记(4) -- 弹窗 & 计时事件 & cookie

    弹窗 可以在 JavaScript 中创建三种消息框:警告框.确认框.提示框. 警告框:经常用于确保用户可以得到某些信息. 当警告框出现后,用户需要点击确定按钮才能继续进行操作. 语法: window ...

  9. 一个简单有效的兼容IE7浏览器的办法

    最近发现了一个简单有效的兼容IE7浏览器的办法 直接将下面代码复制道页面 <meta http-equiv="X-UA-Compatible" content="I ...

  10. [LeetCode] Min Stack 栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...