Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 从文件读取时处理N错误?_Objective C_Cocoa - Fatal编程技术网

Objective c 从文件读取时处理N错误?

Objective c 从文件读取时处理N错误?,objective-c,cocoa,Objective C,Cocoa,我只是好奇我是否做得对 NSString *fileContents; NSError *fileError = nil; fileContents = [[NSString stringWithContentsOfFile:fileOnDisk encoding:NSMacOSRomanStringEncoding error:&fileError] retain]; i

我只是好奇我是否做得对

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];

编辑(以反映bbums评论)

加里

这是不正确的。在检查fileContents是否为nil之前,不能假设fileError的returnby reference值。从来没有。在调用引用传递错误方法之前,将
fileError
设置为nil没有任何用处

也就是说,您的代码应为(现在已修复,因为我不再从一架飞机到另一架飞机运行,也不再在连接之间的WiFi上跳跃……):


bbum,你的意思是
if(fileContents==nil){
?苹果的文档中描述了这一点:谢谢bbum,我可以看到你去哪里了,我也可以看到现在检查fileContents是否为nil更有意义。但是,这不是同样的区别吗?如果fileContents为nil,你不会只得到一个错误。当然,除非存在fileContents不是nil和eir是一个错误。谢谢你的提示。同样在你的新版本中,你是否仍然需要设置NSError*fileError=nil;这似乎有点毫无意义,因为你现在正在检查文件内容?你能不能改为编辑NSError*fileError;?以修复我的仓促回答。很抱歉。是的——不需要初始化fileError,因为除非你先阅读它检查方法的返回值以确定是否确实发生了错误。
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;
NSError *fileError = nil;
....
if(fileError != nil)
....
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];