从文件读取时处理NSError?

fuz*_*oat 14 cocoa objective-c

如果我这样做,我只是很好奇.

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];
Run Code Online (Sandbox Code Playgroud)

.

编辑(反映bbums评论)

.

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;
Run Code Online (Sandbox Code Playgroud)

加里

bbu*_*bum 48

NSError *fileError = nil;
....
if(fileError != nil)
....
Run Code Online (Sandbox Code Playgroud)

那是不对的.你,直到你检查是否fileContents几乎等于零不能假定有关fileError返回按引用任何有价值的东西.永远不会.fileError在调用pass-error-by-reference方法之前设置为nil没有任何用处.

也就是说,你的代码应该读取(现在修复我不再从一个平面到另一个平面运行并在连接之间跳过WiFi ......):

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];
Run Code Online (Sandbox Code Playgroud)

  • bbum,你的意思是`if(fileContents == nil){`? (7认同)
  • 这在Apple的文档中有描述:http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-SW2 (5认同)
  • 编辑修复我匆忙的回答.对于那个很抱歉.是 - 无需初始化fileError,因为您*从不*读取它*除非*您首先检查方法的返回值以确定实际发生错误. (3认同)