![[Cocoa]深入浅出 Cocoa 之 Core Data(2)- 手动编写代码,第1张 [Cocoa]深入浅出 Cocoa 之 Core Data(2)- 手动编写代码,第1张](/aiimages/%5BCocoa%5D%E6%B7%B1%E5%85%A5%E6%B5%85%E5%87%BA+Cocoa+%E4%B9%8B+Core+Data%EF%BC%882%EF%BC%89-+%E6%89%8B%E5%8A%A8%E7%BC%96%E5%86%99%E4%BB%A3%E7%A0%81.png)
深入浅出 Cocoa 之 Core Data(2)- 代码示例
罗朝辉( http://blog.csdn.net/kesalin)
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() 方法修改为如下:
int main (int argc,const char * argv[]){ NSLog(@" === Core Data Tutorial ==="); // Enable GC // objc_startCollectorThread(); return 0;} 二,创建并设置模型类
在 main() 之前添加如下方法:
NSManagedobjectModel *managedobjectModel(){ static NSManagedobjectModel *moModel = nil; if (moModel != nil) { return moModel; } moModel = [[NSManagedobjectModel alloc] init]; // Create the entity // NSEntityDescription *runEntity = [[NSEntityDescription alloc] init]; [runEntity set@R_403_6889@:@"Run"]; [runEntity setManagedobjectClass@R_403_6889@:@"Run"]; [moModel setEntitIEs:[NSArray arrayWithObject:runEntity]]; // Add the Attributes // NSAttributeDescription *dateAttribute = [[NSAttributeDescription alloc] init]; [dateAttribute set@R_403_6889@:@"date"]; [dateAttribute setAttributeType:NSDateAttributeType]; [dateAttribute setoptional:NO]; NSAttributeDescription *IDAttribute = [[NSAttributeDescription alloc] init]; [IDAttribute set@R_403_6889@:@"processID"]; [IDAttribute setAttributeType:NSInteger32AttributeType]; [IDAttribute setoptional:NO]; [IDAttribute setDefaultValue:[NSNumber numberWithInteger:-1]]; // Create the valIDation predicate for the process ID. // The following code is equivalent to valIDationPredicate = [nspredicate predicateWithFormat:@"SELF > 0"] // NSExpression *lhs = [NSExpression ExpressionForEvaluatedobject]; NSExpression *rhs = [NSExpression ExpressionForConstantValue:[NSNumber numberWithInteger:0]]; nspredicate *valIDationPredicate = [NSComparisonPredicate predicateWithleftExpression:lhs rightExpression:rhs modifIEr:NSDirectPredicateModifIEr type:NSGreaterThanPredicateOperatorType options:0]; Nsstring *valIDationWarning = @"Process ID < 1"; [IDAttribute setValIDationPredicates:[NSArray arrayWithObject:valIDationPredicate] withValIDationWarnings:[NSArray arrayWithObject:valIDationWarning]]; // set the propertIEs for the entity. // NSArray *propertIEs = [NSArray arrayWithObjects: dateAttribute,IDAttribute,nil]; [runEntity setPropertIEs:propertIEs]; // Add a Localization Dictionary // NSMutableDictionary *localizationDictionary = [NSMutableDictionary dictionary]; [localizationDictionary setobject:@"Date" forKey:@"Property/date/Entity/Run"]; [localizationDictionary setobject:@"Process ID" forKey:@"Property/processID/Entity/Run"]; [localizationDictionary setobject:@"Process ID must not be less than 1" forKey:@"ErrorString/Process ID < 1"]; [moModel setLocalizationDictionary:localizationDictionary]; return moModel;} 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/nonlocalizedEntity@R_403_6889@" | "LocalizedEntity@R_403_6889@" | |
| "Property/nonlocalizedProperty@R_403_6889@/Entity/Entity@R_403_6889@" | "LocalizedProperty@R_403_6889@" | |
| "Property/nonlocalizedProperty@R_403_6889@" | "LocalizedProperty@R_403_6889@" | |
| "ErrorString/nonlocalizedErrorString" | "LocalizedErrorString" | |
三,创建并设置运行时类和对象
由于要用到存储功能,所以我们必须定义持久化数据的存储路径。我们在 main() 之前添加如下方法设置存储路径:
NSURL *applicationLogDirectory(){ Nsstring *LOG_DIRECTORY = @"CoreDataTutorial"; static NSURL *ald = nil; if (ald == nil) { NSfileManager *fileManager = [[NSfileManager alloc] init]; NSError *error = nil; NSURL *libraryURL = [fileManager URLForDirectory:NSlibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error]; if (libraryURL == nil) { NSLog(@"Could not access library directory\n%@",[error localizedDescription]); } else { ald = [libraryURL URLByAppendingPathComponent:@"Logs"]; ald = [ald URLByAppendingPathComponent:LOG_DIRECTORY]; NSLog(@" >> log path %@",[ald path]); NSDictionary *propertIEs = [ald resourceValuesForKeys:[NSArray arrayWithObject:NSURlisDirectoryKey] error:&error]; if (propertIEs == nil) { if (![fileManager createDirectoryAtPath:[ald path] withIntermediateDirectorIEs:YES attributes:nil error:&error]) { NSLog(@"Could not create directory %@\n%@",[ald path],[error localizedDescription]); ald = nil; } } } } return ald;} 在上面的代码中,我们将持久化数据文件保存到路径: /Users/kesalin/library/Logs/CoreDataTutorial 下。
下面,我们来创建运行时对象:ManagedobjectContext 和 PersistentStoreCoordinator。
NSManagedobjectContext *managedobjectContext(){ static NSManagedobjectContext *moContext = nil; if (moContext != nil) { return moContext; } moContext = [[NSManagedobjectContext alloc] init]; // Create a persistent store coordinator,then set the coordinator for the context. // NSManagedobjectModel *moModel = managedobjectModel(); NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedobjectModel:moModel]; [moContext setPersistentStoreCoordinator: coordinator]; // Create a new persistent store of the appropriate type. // Nsstring *STORE_TYPE = NSXMLStoreType; Nsstring *STORE_file@R_403_6889@ = @"CoreDataTutorial.xml"; NSError *error = nil; NSURL *url = [applicationLogDirectory() URLByAppendingPathComponent:STORE_file@R_403_6889@]; NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE configuration:nil URL:url options:nil error:&error]; if (newStore == nil) { NSLog(@"Store Configuration Failure\n%@",([error localizedDescription] != nil) ? [error localizedDescription] : @"UnkNown Error"); } return moContext;} 在上面的代码中:
1)我们创建了一个全局 ManagedobjectContext 对象 moContext;
2)并在设置其 persistent store coordinator,存储类型为 xml,保存文件名为:CoreDataTutorial.xml,并将其放到前面定义的存储路径下。
好,至此万事具备,只欠 Managedobject 了!下面我们就来定义这个数据对象类。向工程添加 Core Data->NSManagedobject subclass 的类,名为 Run (模型中 Entity 定义的类名) 。
Run.h
#import <CoreData/NSManagedobject.h>@interface Run : NSManagedobject{ NSInteger processID;}@property (retain) NSDate *date;@property (retain) NSDate *primitiveDate;@property NSInteger processID;@end Run.m
//// Run.m// CoreDataTutorial//// Created by kesalin on 8/29/11.// copyright 2011 kesalin@gmail.com. All rights reserved.//#import "Run.h"@implementation Run@dynamic date;@dynamic primitiveDate;- (voID) awakeFromInsert{ [super awakeFromInsert]; self.primitiveDate = [NSDate date];}#pragma mark -#pragma mark Getter and setter- (NSInteger)processID { [self willAccessValueForKey:@"processID"]; NSInteger pID = processID; [self dIDAccessValueForKey:@"processID"]; return pID;}- (voID)setProcessID:(NSInteger)newProcessID{ [self willChangeValueForKey:@"processID"]; processID = newProcessID; [self dIDChangeValueForKey:@"processID"];}// Implement a setNilValueForKey: method. If the key is “processID” then set processID to 0.//- (voID)setNilValueForKey:(Nsstring *)key { if ([key isEqualToString:@"processID"]) { self.processID = 0; } else { [super setNilValueForKey:key]; }}@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() 中代码如下:
int main (int argc,const char * argv[]){ NSLog(@" === Core Data Tutorial ==="); // Enable GC // objc_startCollectorThread(); NSError *error = nil; NSManagedobjectModel *moModel = managedobjectModel(); NSLog(@"The managed object model is defined as follows:\n%@",moModel); if (applicationLogDirectory() == nil) { exit(1); } NSManagedobjectContext *moContext = managedobjectContext(); // Create an Instance of the Run Entity // NSEntityDescription *runEntity = [[moModel entitIEsBy@R_403_6889@] objectForKey:@"Run"]; Run *run = [[Run alloc] initWithEntity:runEntity insertIntoManagedobjectContext:moContext]; nsprocessInfo *processInfo = [nsprocessInfo processInfo]; run.processID = [processInfo processIDentifIEr]; if (![moContext save: &error]) { NSLog(@"Error while saving\n%@",([error localizedDescription] != nil) ? [error localizedDescription] : @"UnkNown Error"); exit(1); } // Fetching Run Objects // NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:runEntity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; error = nil; NSArray *array = [moContext executeFetchRequest:request error:&error]; if ((error != nil) || (array == nil)) { NSLog(@"Error while fetching\n%@",([error localizedDescription] != nil) ? [error localizedDescription] : @"UnkNown Error"); exit(1); } // display the Results // NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateStyle:NSDateFormatterMediumStyle]; [formatter setTimeStyle:NSDateFormatterMediumStyle]; NSLog(@"%@ run history:",[processInfo process@R_403_6889@]); for (run in array) { NSLog(@"On %@ as process ID %ld",[formatter stringForObjectValue:run.date],run.processID); } return 0;} 在上面的代码中:
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)将查询结果打印输出;
大功告成!编译运行,我们可以得到如下显示:
2011-09-03 21:42:47.556 CoreDataTutorial[992:903] CoreDataTutorial run history:2011-09-03 21:42:47.557 CoreDataTutorial[992:903] On 2011-9-3 下午09:41:56 as process ID 9402011-09-03 21:42:47.557 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:16 as process ID 9552011-09-03 21:42:47.558 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:20 as process ID 9652011-09-03 21:42:47.558 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:24 as process ID 9782011-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]深入浅出 Cocoa 之 Core Data(2)- 手动编写代码全部内容,希望文章能够帮你解决[Cocoa]深入浅出 Cocoa 之 Core Data(2)- 手动编写代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)