从文件读取时处理NSError? [英] Handling NSError when reading from file?
本文介绍了从文件读取时处理NSError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是好奇,如果我这样做。
I am just curious if I am doing this right.
NSString *fileContents;
NSError *fileError = nil;
fileContents = [[NSString stringWithContentsOfFile:fileOnDisk
encoding:NSMacOSRomanStringEncoding
error:&fileError] retain];
if(fileError != nil) {
NSLog(@"Error : %@", [fileError localizedDescription]);
}
// Other Code ...
[fileContents release];
。
。
NSString *fileOnDisk = @"/Users/Gary/Documents/Xcode/RnD/Maya.MEL";
NSError *fileError; // Should this be *fileError = nil;
NSString *fileContents;
int status = 0;
fileContents = [[NSString stringWithContentsOfFile:fileOnDisk
encoding:NSMacOSRomanStringEncoding
error:&fileError] retain];
if(fileContents == nil) {
NSLog(@"FileError: %@", [fileError localizedDescription]);
status = 1;
} else {
NSLog(@"Success : %@", fileContents);
}
// Clean up
[fileContents release];
[pool drain];
return status;
gary
推荐答案
NSError *fileError = nil;
....
if(fileError != nil)
....
b $ b
这不正确。在检查fileContents是否为nil 之前,您不能假定fileError的返回引用值。永远不会。在调用引用传递错误引用方法之前将 fileError
设置为nil无效。
That is incorrect. You must not assume anything about the return-by-reference value of fileError until you check whether or not fileContents was nil. Not ever. Setting fileError
to nil prior to calling the pass-error-by-reference method does nothing useful.
,你的代码应该读取(现在修正,我不再运行从飞机到飞机和跳跃在WiFi连接之间...):
That is, your code should read (fixed now that I'm no longer running from plane to plane and hopping on WiFi in between connections...):
NSString *fileContents;
NSError *fileError;
fileContents = [[NSString stringWithContentsOfFile:fileOnDisk
encoding:NSMacOSRomanStringEncoding
error:&fileError] retain];
if(fileContents == nil) {
NSLog(@"Error : %@", [fileError localizedDescription]);
// ... i.e. handle the error here more
return ...; // often returning after handling the errors, sometimes you might continue
}
// Other Code ...
[fileContents release];
这篇关于从文件读取时处理NSError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文