Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Best practice in objective c for creating an object and setting its properties

Considering I have a UIViewController called ErrorViewController that I am instantiating using initWithNibName.

There is a enum on this ErrorViewController describing its "type".

This ErrorViewController has one delegate function that returns to its delegate which will respond according to the type set on the ErrorViewController.

Is it better to pass all the parameters within a new initWithNibName function, and set private properties on the ErrorViewController. Like this:

ErrorViewController *errorVc = [[ErrorViewController alloc] 
initWithNibName:@"ErrorViewController" bundle:nil 
andErrorType:kErrorTypeA andDelegate:self];

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
andErrorType:(ErrorType)errorType andDelegate:(id<ErrorDelegate>)delegate{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.delegate = delegate;
        self.errorType = errorType;
    }
    return self;
}

Or is it better to instantiate the object and afterward set its public properties like this:

ErrorViewController *errorVc = [[ErrorViewController alloc] 
initWithNibName:@"ErrorViewController" bundle:nil];
errorVc.delegate = self;
errorVc.type = kErrorTypeA.

And regarding the delegate method, is it best practice to check the type by passing a parameter, or by checking the property of the passed back Controller as follows:

- (void)ErrorPage:(ErrorViewController *)ErrorPage 
// check ErrorPage.errorType
}

or this: ?

- (void)ErrorPage:(ErrorViewController *)ErrorPage 
andErrorType:(ErrorType)errorType
// check errorType
}
like image 426
cohen72 Avatar asked Nov 26 '25 05:11

cohen72


1 Answers

I think it's a question of preference. If the object can't function correctly without error-type and/or delegate, it's probably best to provide your custom initialiser.

As to your second question, I would provide the error type as in your second example. Note that the method name should start with a lowercase character though (-errorPage: instead of -ErrorPage:).

Additionally, if you use it a lot, I would provide a convenience class method to create the object:

+(ErrorViewController*) standardErrorViewControllerWithErrorType: (ErrorType) errorType andDelegate: (id<ErrorDelegate>) delegate {

  ErrorViewController *evc = [[ErrorViewController alloc] initWithNibName: @"ErrorViewController" bundle: nil andErrorType: errorType andDelegate: delegate];
return evc;
}

Edit

Also, in your init method, it is encouraged to use -(instancetype) init... instead of -(id) init....

like image 107
Mario Avatar answered Nov 27 '25 20:11

Mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!