Reputation: 7334
I am in a situation where I have to create an init
with a parameter.
- (id) initWithSomeParameter:(id)parameter;
Normal init
should not be called. So, I have two choices to accomplish this. I can actually throw an exception when some one calls the init
or return nil
.
Which should be done and why?
Upvotes: 2
Views: 1870
Reputation: 187222
It's hard to say without knowing more about your use case. However, Perhaps you are being too strict with your API.
UIKit
itself is full of classes that need some data to operate, but don't require it on init. Take UIImageView
for example. You may think "an image view requires an image to do anything, therefore I should require an image on init!". However, this snippet here is a perfectly valid use case:
UIImageView *foo = [[UINavigationController alloc] init];
foo.image = [UIImage imageNamed:@"bar"];
Here we make an image view, and assign the image itself in a second step. So instead throw exceptions when you try to use your object in ways that require data to be present if that data isn't present.
Also, your designated initializer is usually the one that typically takes the most arguments, and the rest call that one. Something kind of like this may be more what you want.
- (id)init {
// call this class's designated initializer
return [self initWithSomething:nil];
}
// this class's designated initializer
- (id)initWithSomething:(NSString*)something {
self = [super init]; // call superclass's designated initializer
if (self) {
// this class's setup code goes here, saving any arguments
somethingInstanceVar = something;
}
return self;
}
// some other method.
- (NSString*)doSomething {
if (somethingInstanceVar) {
// all is well, do stuff
return somethingInstanceVar;
} else {
// never got a "something" raise an exception
[NSException raise:@"Missing data" format:@"Something is required!"];
}
}
Upvotes: 4
Reputation: 12663
You should have a designated initializer, which all other init
methods call.
In your example, the designated initializer would perhaps be
- (id)initWithSomeParameter:(id)something;
If another programmer calls -(id)init
instead of the designated initializer, you might do something like this:
- (id)init
{
return [self initWithSomeParameter:nil];
}
If you absolutely must have a value provided for someParameter
, you can raise an exception if you choose to, but this practice varies with how important getting a value is on initialization of the instance object.
Here's Apple's input also on using a designated initializer:
Upvotes: 4