开发者

Content is not retrieved from file

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开发者_如何学Python 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...


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜