Search code examples
iphoneiosplistnsdatanskeyedarchiver

How to convert NSData to NSArray (or NSObject)


I did test this code, but it cause SIGABRT error.

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]

NSData is plist data with xml format. This code works fine.

[urlData writeToFile:[self docPath] atomically:YES];
array = [[NSMutableArray alloc] initWithContentsOfFile:[self docPath]];

How can I change NSData to NSArray without file conversion?


Solution

  • This assumes you have populated NSString *filepath with the filepath of your saved data file.

    NSPropertyListFormat format;
    NSData *dataFromFile = [NSData dataWithContentsOfFile:fileNameWithPath];
    NSArray *arrayFromFile = nil;
    if (dataFromFile) {
        arrayFromFile = [NSPropertyListSerialization propertyListFromData:dataFromFile
                                                           mutabilityOption:NSPropertyListMutableContainers
                                                                     format:&format 
                                                           errorDescription:nil];
    }
    

    Hope that helps...