I have a NSMutableArray and a NSString . These two are archived to NSData and add to a NSMutableData Object.

How can I access each data from NSMutableData Object.

NSData *dataArray= [NSKeyedArchiver archivedDataWithRootObject:mutableArray];
NSData *dataTouchedNumer=[NSKeyedArchiver archivedDataWithRootObject:stringValue];                
NSMutableData *mutableData=[[NSMutableData alloc]init];
[mutableData appendData:dataArray];
[mutableData appendData:dataTouchedNumer];
有帮助吗?

解决方案

You can't do this the way you are showing. If you append two NSData objects together into a single mutable data object, there is no way to separate them later. Try this instead:

To archive the two objects:

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"];

At this point, data contains the two objects. Do what you need with the data (save it for example).

To get your objects back:

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

其他提示

According to the docs, "archivedDataWithRootObject: returns an NSData object containing the encoded form of the object graph whose root object is given." So your mutableData object contains 2 such encoded object graphs. The question is what kind of data you want to read out of mutableData. It probably does not make much sense, to read simply all bytes with [mutableData bytes], or part of it with getBytes:length: or getBytes:range:.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top