2010-07-01 114 views

回答

32

使用的NSKeyedArchiver

要的NSDictionary轉換爲NSData的

NSMutableData *data = [[NSMutableData alloc]init]; 
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; 
[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY]; 
archiver finishEncoding]; 
[data writeToFile:YOURFILEPATH atomically:YES]; 
[data release]; 
[archiver release]; 

從存儲的NSData的

NSData *data = [[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH]; 
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 
YOURDICTIONARY = [unarchiver decodeObjectForKey: YOURDATAKEY]; 
[unarchiver finishDecoding]; 
[unarchiver release]; 
[data release]; 
2

一個更簡單的版本羅伯特的回答得到的NSDictionary回:

[NSKeyedArchiver archiveRootObject:YOURDICTIONARY toFile:YOURFILEPATH]; 

,並相應:

YOURDICTIONARY = [NSKeyedUnarchiver unarchiveObjectWithFile:YOURFILEPATH]; 

或者爲原來,而不歸咎於一個文件分成東西來回答這個問題:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:YOURDICTIONARY]; 
... 
YOURDICTIONARY = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 

它的所有工廠方法,所以它是有或沒有ARC相同的代碼;自第一天起,OS X v10.2和iOS上已使用所用的方法。

相關問題