Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSError: Does using nil to detect Error actually turn off error reporting?

I got into the habit of coding my error handling this way:

 NSError* error = nil;
 NSDictionary *attribs = [[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error];
 if (error != nil) {
  DLogErr(@"Unable to remove file: error %@, %@", error, [error userInfo]);
  return; 
 }  

But looking at the documentation It seems like I got this wrong.:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Technically there is no difference between nil and NULL so does this mean I'm actually turning this off and will never get a error message (even if the delete in the above example did fail) ? Is there a better way to code this ?

Thanks.

like image 658
EtienneSky Avatar asked Jan 17 '11 23:01

EtienneSky


1 Answers

First off, the following line doesn't really make sense:

NSDictionary *attribs = [[NSFileManager defaultManager]
 removeItemAtPath:fullPath error:&error];

-removeItemAtPath:error: returns a BOOL value, not a dictionary.

I think I see what you’re wondering about with the NULL value. Notice carefully though, how there are 2 *'s in the error parameter in the method signature:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

That means a pointer to a pointer. When you pass in &error, you are passing in the address of the pointer to the NSError. (Ugh, someone else can probably help me out here, as my head still starts to swim when dealing with pointers to pointers). In other words, even though you have set error to nil, you aren't passing in error to the method, you're passing in &error.

So, here’s what the re-written method should look like:

// If you want error detection:
NSError *error = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:fullPath
            error:&error]) {
    NSLog(@"failed to remove item at path; error == %@", error);
    // no need to log userInfo separately
    return;
}

// If you don't:
if (![[NSFileManager defaultManager] removeItemAtPath:fullPath
            error:NULL]) {
    NSLog(@"failed to remove item at path");
    return;
}
like image 177
NSGod Avatar answered Oct 14 '22 09:10

NSGod