The default construction usually start with has the following format -init
or any variant upon this, e.g. -initWithFrame:
.
The method +initialize
is a class method (static method) that’s called at least once when your application starts. You can use this method to initialize static variables that are useful across all instances of the class. This method might be useful to e.g. initialize a shared cache or a shared lookup map for a class.
For NSObject
the -init
method is the designated initializer, but for other classes this might differ. Apple documents the designated initializer in it’s class headers using the NS_DESIGNATED_INITIALIZER
macro. For example UIView
subclasses should override -initWithFrame:
and -initWithCoder:
instead, as these methods are marked as designated initializer.
When subclassing and implementing a custom designated initializer, don’t forget to initialize the super class as well. Let’s for example have a UIView
subclass that has a custom designated initializer -initWithFrame:title:
. We would implement it as follows:
// A custom designated initializer for an UIView subclass.
- (id)initWithFrame:(CGRect)frame title:(NSString *)title
{
// Initialize the superclass first.
//
// Make sure initialization was successful by making sure
// an instance was returned. If initialization fails, e.g.
// because we run out of memory, the returned value would
// be nil.
self = [super initWithFrame:frame];
if (self)
{
// Superclass successfully initialized.
self.titleLabel.text = title
}
return self;
}
// Override the designated initializer from the superclass to
// make sure the new designated initializer from this class is
// used instead.
- (id)initWithFrame:(CGRect)frame
{
return [[self alloc] initWithFrame:frame title:@"Untitled"];
}
More details on initialising can be found on the Apple Developer website:
-
Object Initialization
-
Multiple Initializers