Question

The following is commonplace in Objective-C.

- (id)init {
    if (self = [super init]) {
        // custom initialization
    }
    return self;
}

Because -init is an instance method, it must be called on a valid instance of a class, and an instance of a class must be instantiated. This instantiation uses up memory. Does calling -init on super use memory as it has to instantiate a new object to call the init method on?

Was it helpful?

Solution

Does calling -init on super use memory as it has to instantiate a new object to call the init method on?

No, because your premise is false. super, as the receiver of a message, is the same object as self; it's just a signal to the compiler to use objc_msgSendSuper() instead of objc_msgSend(). The former starts method lookup with the superclass, but the instance that runs the method is still the same.

No new instance is created by using the super keyword.

OTHER TIPS

It all depends on what's going on up the chain.

If it's simply "[NSObject init]", then nothing (obvious) is happening.

But if it's "[BrianTracySuperAwesomeBaseClass init]" with a lot of initialization and setting up various ivars and properties, then yes, you're using a bit of memory.

In general, you shouldn't load down your "init" methods with lots of stuff going on... instead you should rely on lazy loading or allocate-on-demand things for your Objective C objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top