Handling NSError when reading from file?

后端 未结 1 535
执念已碎
执念已碎 2020-12-08 22:43

I am just curious if I am doing this right.

NSString *fileContents;    
NSError *fileError = nil;

fileContents = [[NSString stringWithContentsOfFile:fileOn         


        
相关标签:
1条回答
  • 2020-12-08 23:08
    NSError *fileError = nil;
    ....
    if(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.

    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];
    
    0 讨论(0)
提交回复
热议问题