0

I'm trying to write my NSMutableArray to a text file. I looked at the data with NSLog before I write it, and it's in the format I want

String \t integer \t integer \t integer \r\n
String \t integer \t integer \t integer \r\n
... (50 lines like this)
String \t integer \t integer \t integer \r\n

I write the file by:

[NSKeyedArchiver archiveRootObject:myMutableArray toFile:newPath];

When I look at the file on disk however, it is a bunch of gibberish. Am I doing something wrong here? Or am I understanding how archiveRootObject:toFile: works incorrectly? Thanks.

Crystal
  • 28,460
  • 62
  • 219
  • 393

3 Answers3

0

Step 1: if custom objects (say class objects ) are used then

-(id) initWithCoder:(NSCoder *)aDecoder

-(void) encodeWithCoder:(NSCoder *)aCoder

methods in your custom class and have to use NSCoding protocol

Step 2: in order to retrieve the data from the .bin file

NSFileManager * fm = [NSFileManager defaultManager];
NSURL * docsURL =[fm URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
// this will create the file yourFile.bin if it is not present    
NSString * path = [[docsURL path]stringByAppendingString:@"/yourFile.bin"];

self.yourArray = [NSKeyedUnarchiver unarchiveObjectWithFile:self.path];

Step 3: if you want to save the data on to a .bin file

NSFileManager * fm = [NSFileManager defaultManager];
NSURL * docsURL =[fm URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

this will uses your file if present else it will create it

NSString * path = [[docsURL path]stringByAppendingString:@"/yourFile.bin"];

[NSKeyedArchiver archiveRootObject:self.recordedPlayers toFile:self.path]

that's it, your code should work properly by storing data on to file and retrieve it when you ask for it...

Hope this will solve the problem

fishinear
  • 6,101
  • 3
  • 36
  • 84
Rony
  • 465
  • 2
  • 6
  • 14
0

You can't examine the file directly as it's written in a binary format. You'll have to load it back in order to read it.

See the discussion in the documentation.

kevboh
  • 5,207
  • 5
  • 38
  • 54
0

As others have noted, the file is written in a binary format.

You can, however examine it - it's a binary plist, so simply naming (or renaming in Finder) to a .plist extensions and opening with Xcode will show you the contents of the keyed archive. The organization of the keys isn't immediately obvious, but if you're looking for a specific value, you can usually find/edit it quite easily:

screenshot from Xcode plist editor

ckhan
  • 4,771
  • 24
  • 26