Thursday, January 6, 2011

Default Init in iOS (Obj-C)

The standard advice is to use a "designated initializer" which ends up with me having to think, which is always bad. Here is a pattern that never fails, and you could put it in a UIView category (UIView+SharedInit) and be done with this forever.

- (void) sharedInit {
}

- (id) init
{
self = [super init];
if (self != nil) {
[self sharedInit];
}
return self;
}


-(id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
[self sharedInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
[self sharedInit];
    }
    return self;
}

This is for a UIView subclass only, of course, but you could do the same thing for other classes as well.

No comments: