2013-05-13 56 views
0

我有一個NSMutableArray和一個NSString。這兩個存檔到NSData並添加到一個NSMutableData對象。如何從NSMutableData訪問對象

如何從NSMutableData對象訪問每個數據。

NSData *dataArray= [NSKeyedArchiver archivedDataWithRootObject:mutableArray]; 
NSData *dataTouchedNumer=[NSKeyedArchiver archivedDataWithRootObject:stringValue];     
NSMutableData *mutableData=[[NSMutableData alloc]init]; 
[mutableData appendData:dataArray]; 
[mutableData appendData:dataTouchedNumer]; 
+0

你能告訴我們更多的代碼? – Rivers 2013-05-13 12:25:31

+0

我只需要如何從mutableData訪問數據。 – 2013-05-13 12:32:11

回答

0

你不能這樣做,你正在顯示。如果將兩個NSData對象一起追加到單個可變數據對象中,以後就無法將它們分開。試試這個:

要存檔的兩個對象:

NSMutableArray *mutableArray = ... // your mutable array 
NSString *stringValue = ... // your string 

NSMutableData *data = [NSMutableData data]; 
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 
[archiver encodeObject:mutableArray forKey:@"array"]; 
[archiver encodeObject:stringValue forKey:@"string"]; 

在這一點上,data包含了兩個對象。做你所需要的數據(例如保存)。

爲了讓您的對象回來:

NSData *data = ... // the archived data 
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 
NSMutableArray *mutableArray = [unarchiver decodeObjectForKey:@"array"]; 
NSString *stringValue = [unarchiver decodeObjectForKey:@"string"]; 
0

根據the docs,「archivedDataWithRootObject:返回包含對象圖的根對象被賦予的編碼形式的NSData對象」。所以你的mutableData對象包含2個這樣的編碼對象圖。問題是你想從mutableData中讀出什麼樣的數據。使用[mutableData bytes]簡單地讀取所有字節,或者使用getBytes:length:getBytes:range:來讀取所有字節可能沒有多大意義。