-(id)init methods, NSExceptions, and returning nil
-(id)init methods, NSExceptions, and returning nil
- Subject: -(id)init methods, NSExceptions, and returning nil
- From: William Squires <email@hidden>
- Date: Mon, 27 Jun 2011 08:22:19 -0500
The favored form for writing an init method seems to be
-(id)init
{
if (self = [super init])
{
// Do something here
}
return self;
}
Several questions arise:
1) Isn't the 'if' superfluous? if self was nil (after the assignment from [super init]), any messages sent (in the commented section) to it would do nothing. The real problem would be if you accessed the instance variables directly to initialize them to some non-zero value.
2) Isn't the prevailing paradigm to raise an NSException if something goes wrong? In which case, maybe the above code should be more like:
-(id)init
{
if (!(self = [super init]))
{
// Raise an NSException here
}
// Do initializations here
return self;
}
or is 'init'ing a special case?
What if I have an init method, and - in the above '// Do something here' section - my initializations fail (maybe a resource can't be located/loaded) - should I raise an NSException, or set self=nil so that any subclasses will get a nil when they call my class' init through the [super init] part?
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden