Search code examples
iosobjective-cnskeyedarchivernsmutabledata

How to access objects from NSMutableData


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

Solution

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