문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top