2012-10-26 35 views
0

我正在一個項目中,我有各種自定義對象。這些自定義對象(其中一些與嵌套的可變數組一起工作)需要保存到一個或多個文件中。這樣做最好的方法是什麼?我應該創建一個負載保存文件管理器或者讓每個對象處理它是一個更好的主意嗎?編碼和解碼 - 自定義對象和實現

謝謝你的時間。

- 史蒂芬

回答

1

爲你的類實現NSCoding協議:

NSString * const kMyArray = @"myString"; 
NSString * const kMyBool = @"myBool"; 

- (void)encodeWithCoder:(NSCoder *)coder 
{ 
    [coder encodeObject:_myArray forKey:kMyArray]; 
    [coder encodeBool:_myBool forKey:kMyBool]; 
    //... 
} 

- (id)initWithCoder:(NSCoder *)coder 
{ 
    self = [super init]; 
    if (self) { 
     _myArray = [coder decodeObjectForKey:kMyArray]; 
     _myBool = [coder decodeBoolForKey:kMyBool]; 
     //... 
    } 
    return self; 
} 

,讓您保存和NSKeyedArchiver加載數據:

//saving collection of Class<NSCoding> objects 
NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; 
BOOL success = [NSKeyedArchiver archiveRootObject:_collection toFile:path]; 

//loading 
NSData *data = [[NSData alloc] initWithContentsOfFile:path]; 
if (data) _collection = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
+0

非常好。我最初嘗試實現遵循NSCoding協議的Load/Save對象以及遵循同一協議的每個自定義對象。然而,它變得一塌糊塗。所以現在我要做的是讓每個對象類型都自己保存文件,因爲這些對象屬於不同的部分,並且可以很好地分開。 –

0

如果你想編碼和解碼對象,你可以看看NSCoding。這是一個簡單的方法。

取文檔中一看:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html

更新在iOS版本,存儲的對象變成了腐敗,當我有問題(編輯正確的鏈接)。這是圍繞從iOS 4.1到iOS 4.2的過渡。

我停止使用NSCoder並切換到創建具有基礎JSON文件的自定義文件格式。現在我對文件版本控制有了更多的控制,並且可以很容易地進行修復,因爲它只是解釋您自己的數據文件。

0

您可以在應用程序包中手動創建一個plist文件(假設Config.plist是plist的名稱),並將其複製到Document目錄後,可以通過編程方式對其進行修改。

所以看這裏如何將文件複製到文檔目錄:所有的 首先定義兩個宏:

#define DOCUMENT_DIR  [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 
#define PLIST_SETTINGS  [DOCUMENT_DIR stringByAppendingPathComponent:@"Config.plist"] 

之後 -

NSString *configPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"]; 
[self copyIfNeededFrom:configPath To:PLIST_SETTINGS]; 
NSMutableArray* mArrObjects = [NSMutableArray alloc] initWithObjects:obj1,obj2,obj3, nil]; 
[mArrObjects writeToFile:PLIST_SETTINGS atomically:YES]; 
[mArrObjects release]; 

現在給copyIfNeededFrom的定義:以:

- (BOOL)copyIfNeededFrom:(NSString *)sourcePath To:(NSString *)destinationPath 
{ 
NSError *error = noErr; 
if(![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) 
{ 
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error]; 
} 
if(noErr) 
    return YES; 
else 
    return NO; 
} 

希望它適合你。 乾杯!