8

Fairly simple question:

I have an init method on my class that has the potential to go wrong. If it does, I plan to "return nil", but I would also like to return an error. Is it bad practice to have an NSError** parameter to an init method? My method declaration would look like this:

- (id) initWithArgs:(NSString*) args andError:(NSError**)error;

Many thanks, Nick

dark_perfect
  • 1,438
  • 22
  • 38

1 Answers1

7

It's unusual, but I don't think it's necessarily a bad practice. I'd name the second part of the method just "error" instead of "andError:", though. You don't need to connect the parts of a method name with 'and', and in this case it also gives the impression that the error is being used to initialize the object. Just make it:

- (id) initWithArgs:(NSString*) args error:(NSError**)error;

Also, don't forget to release the allocated object if you plan to return something else (like nil):

- (id) initWithArgs:(NSString*) args error:(NSError**)error
{
    if ((self = [super init])) {
        if (canInitThisObject) {
            // init this object
        }
        else {
            [self release];
            self = nil;
            if (error != nil) {
                *error = [NSError errorWithDomain:someDomain code:someCode: userInfo:nil];
            }
        }
    }
    return self;
}
Sedate Alien
  • 10,572
  • 6
  • 35
  • 57
Caleb
  • 120,112
  • 19
  • 171
  • 259
  • 1
    One thing I would recommend is ALWAYS setting error to nil at the beginning of the method. There's no guarantee that the caller will have zeroed it out. – EricS Mar 25 '12 at 00:54
  • 4
    @EricS There is no reason to set the `error` to `nil` unless there is an error. The caller should never look at `@error`'s value unless the method returns `nil`. To do otherwise is a bug. @Caleb that code needs to check to make sure `error` is non-NULL before assigning to `*error`. – bbum Mar 25 '12 at 01:54
  • 3
    Any sentence beginning with "the caller should" usually leads to disaster in my experience. :-) – EricS Mar 25 '12 at 04:15
  • 1
    Sure -- doesn't change the rules, though. – bbum Mar 25 '12 at 04:30
  • In the age of Swift 2 you might want to keep the andError or use withError – uchuugaka Nov 09 '15 at 01:50
  • 1
    I object to EricS recommendation. Error handling behavior from Apple says "do NOT alter *error unless an error occurred, and the incoming error might point to a previous error that occurred before this call - do not clear it. – Motti Shneor Mar 21 '21 at 18:06