1

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?

Brian Tracy
  • 6,801
  • 2
  • 33
  • 48

2 Answers2

2

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
1

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.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215