views:

62

answers:

1

I have the following bit of code:

NSData *data = [NSData dataWithContentsOfFile:filePath options:0 error:&fileError];
NSString *recipe = @"";
if (fileError == nil) {
     recipe = [NSString stringWithUTF8String:[data bytes]];
     NSLog(@"Converted Recipe as: %@",recipe);
     NSLog(@"Original Data was: %@",data);  
} else {
     NSLog(@"Error reading file: %@", [fileError localizedDescription]);
}

The problem is that sometimes the stringWithUTF8String returns null and sometimes it correctly returns the contents of the file... The SAME file. Sometimes it works and sometimes it doesn't. Here's a snippet from the log when it does not.... Which means to me that the file read is working, but for some reason the conversion has failed this time. If I do it again (this is called as the result of a tableView didSelectRowAtIndexPath: So I can just click on a different row and then come back to this one.

2010-08-01 16:14:29.031 RecipeBrowse[52056:207] Converted Recipe as: (null)
2010-08-01 16:14:29.037 RecipeBrowse[52056:207] Original Data was: <426c6163 6b656e65 64204361 626f2046 69736820 5461636f 730a0a49 4e475245 4449454e 54533a0a 0a2d200a 0a0a4d45 54484f44 3a0a0a42 4c41434b 454e4544 20434142 4f204649 53482054 41434f53 

Any ideas how to make this more reliable??

+2  A: 

+stringWithUTF8String: will assume that its input is a NUL-terminated string, but NSData doesn't put any particular terminator there. Instead, create your string using -initWithBytes:length:encoding:, since you know the length of the data.

JWWalker
Or `initWithData:encoding:`.
Wevah
+1 @Wevah: True, I missed that one.
JWWalker
Brilliant, thank you! That seems to have cleared it up.
Brad Miller