Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-C: NSError in initialiser

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

like image 908
dark_perfect Avatar asked Mar 24 '12 23:03

dark_perfect


1 Answers

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;
}
like image 193
Caleb Avatar answered Oct 19 '22 00:10

Caleb