开发者

stringWithUTF8String fails, but only sometimes

开发者 https://www.devze.com 2023-01-09 14:46 出处:网络
I have the following bit of code: NSData *data = [NSData dataWithContentsOfFile:filePath options:0 error:&fileError];

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??


+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.


Had the same problem, initWithData:data works for me

- (NSString *)base64String {
    NSData * data = [UIImagePNGRepresentation(self) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
0

精彩评论

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