views:

33

answers:

2

Hello,

I've got this wired problem, I cannot get the content from the file and initiate my NSMutableArray with it.

Here's my code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSLog(@"Does file exist?: %i", [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat: @"%@/length.txt", documentsDirectory]]);

NSMutableArray *tempArr;

tempArr = [[NSMutableArray alloc] initWithContentsOfFile:[NSString stringWithFormat: @"%@/length.txt", documentsDirectory]];

When trying this, initWithContentsOfFile returns (null). The row checking if the file exist prints '1' to the console.

This is the code I'm using to save the data:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[length.text writeToFile:[NSString stringWithFormat: @"%@/length.txt", documentsDirectory] atomically:NO];

I'm using more or less exactly the same code in a different program without problems.

Really need some help here, perhaps I'm just blind for the moment...

Thanks in advance!

/Niklas

+2  A: 

When you try to create an array from the contents of a file, the file must be in plist format, and the outer-most plist element must be <array>. If it doesn't have that format, initialization will fail and your array will be nil.

You're creating the file by writing an NSString to a file, which means you should probably be reading it in to an NSString, not an NSArray.

Dave DeLong
+1  A: 

Hi,

The docs for NSArray's initWithContentsOfFile: method say:

Return Value An array initialized to contain the contents of the file specified by aPath or nil if the file can’t be opened or the contents of the file can’t be parsed into an array. The returned object might be different than the original receiver.

You don't include the declaration of length in your code snippet, but I'm guessing that length.text returns an NSString object, not an NSArray. So you'd need to read that back from a file using initWithContentsOfFile: from NSString, not NSArray.

Simon Whitaker
Thanks! I wasn't thinking about the format of the files, they are very different of course. In my other program from which I copied the code, I am both writing and reading using arrays.
Nicsoft
Glad it helped! Sometimes all it takes is a fresh pair of eyes on your code. :)
Simon Whitaker