[Cocoa]深入浅出Cocoa之Core Data(2)- 手动编写代码
深入淺出Cocoa之Core Data(2)- 手動編寫代碼
羅朝輝 (http://www.cnblogs.com/kesalin/)
本文遵循“署名-非商業用途-保持一致”創作公用協議前面詳細講解了 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 setName:@"Run"];
[runEntity setManagedObjectClassName:@"Run"];
[moModel setEntities:[NSArray arrayWithObject:runEntity]];
// Add the Attributes
//
NSAttributeDescription *dateAttribute = [[NSAttributeDescription alloc] init];
[dateAttribute setName:@"date"];
[dateAttribute setAttributeType:NSDateAttributeType];
[dateAttribute setOptional:NO];
NSAttributeDescription *idAttribute = [[NSAttributeDescription alloc] init];
[idAttribute setName:@"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/NonLocalizedEntityName" | "LocalizedEntityName" | ? |
| "Property/NonLocalizedPropertyName/Entity/EntityName" | "LocalizedPropertyName" | ? |
| "Property/NonLocalizedPropertyName" | "LocalizedPropertyName" | ? |
| "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_FILENAME = @"CoreDataTutorial.xml";
NSError *error = nil;
NSURL *url = [applicationLogDirectory() URLByAppendingPathComponent:STORE_FILENAME];
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 entitiesByName] 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 processName]);
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)將查詢結果打印輸出;
?
大功告成!編譯運行,我們可以得到如下顯示:
CoreDataTutorial[992:903] On 2011-9-3 下午09:41:56 as process ID 940
2011-09-03 21:42:47.557 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:16 as process ID 955
2011-09-03 21:42:47.558 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:20 as process ID 965
2011-09-03 21:42:47.558 CoreDataTutorial[992:903] On 2011-9-3 下午09:42:24 as process ID 978
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 為我們代勞了。
轉載于:https://www.cnblogs.com/kesalin/archive/2011/09/03/core_data_tutorial_02.html
總結
以上是生活随笔為你收集整理的[Cocoa]深入浅出Cocoa之Core Data(2)- 手动编写代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CAD迷你看图2019破解版|CAD迷你
- 下一篇: 全国各省统计年鉴汇总2021