Search code examples
objective-cnsmutablearraynsfilemanagertype-conversion

NSMutableArray to NSData to .txt file - output unreadable


I have an NSMutableArray created storing song names and artists. I am trying to convert this array to NSData format so that I can save it to a text file. When attempting to do so, the output I get is unreadable:

bplist00ÔghX$versionX$objectsY$archiverT$top † ¯$ !")-./3459:;?@AEFGKLMQRSWXY]^_cU$nullÒ R$0V$class€€#Ò ZNS.objectsª€€€ € ...etc.

The code I'm using to convert from an NSMutableArray to NSData is:

NSFileManager *fm;

NSData *dataCache = [NSKeyedArchiver archivedDataWithRootObject:myList];

fm = [NSFileManager defaultManager];

if ([fm createFileAtPath:@"/users/nicholasvogler/desktop/Mysongs.txt" contents:dataCache  attributes:nil] == NO)

    {
        NSLog (@"Could not create data file");
        return 1;
    }

All objects in the array are NSStrings and I've added the following method for the strings and the array:

-(void) encodeWithCoder:(NSCoder *)encoder
{

    [encoder encodeObject: songname];
    [encoder encodeObject: artist];
}

Solution

  • What exactly are you expecting the output to be? What you have there is a binary plist. That's what archived data (e.g. NSKeyedArchiver) emits. There's an XML format as well, which can be accessed via NSPropertyListSerialization, although nobody uses the XML format for archived data because the actual plist representation is an implementation detail.

    So despite the fact that it's an unreadable binary blob to you, it still encodes what you want, and you can decode it again with NSKeyedUnarchiver.