Object initialization sequence in Objective-C

The Cocoa structure has a convention that always invokes self = [super init]a method of an initinherited class because it [super init]can return a new instance.

What happens if I do this?

@interface MyClass : NSObject /* or any other class */ {
    int ivar_;
}
@end

@implementation MyClass

- (id)init {
    ivar_ = 12345;

    if ((self = [super init])) {
        NSLog(@"ivar_ value is %d", ivar_);
    }
    return self;
}

@end

In the case when it [super init]returns a new instance, what will I see in the console? ivar_ value is 0?

I can't think of a way to test this myself, because I don't know which class can return a new instance from its method init. Also, it seems it cannot find an explicit explanation for this scenario in the docs.

Can anyone help me out? Thank!

+5
source share
1 answer

, +alloc , . , : a) b) ( 0, C - NULL, - nil ..). , , - , -init . , NSObject, [super init] . , , ,

  • ( ) +alloc MyClass, . , ivar_ 0
  • ( ) -init
  • ivar_ == 12345 - -init, self->ivar_ = 12345. self , +alloc
  • [super init] , ivar_ , (NSObject) , self. , self, .
  • self nil, NSLog()
  • -init self

, [super init] , , +alloc:

  • ( ) +alloc MyClass, . , ivar_ 0
  • ( ) -init
  • ivar_ == 12345 - -init, self->ivar_ = 12345. self , +alloc
  • [super init] , . self, -init . , ivar_ . ivar_ , [super init] ,
  • self nil, NSLog()
  • -init self, , +alloc

. , , , .

#import <Foundation/Foundation.h>

@interface MySuperClass : NSObject
@end

@interface MyClass : MySuperClass
{
  @public
  int ivar_;
}
@end

@implementation MySuperClass

static MyClass *defaultInstance;

- (id)init
{
  if ([self isMemberOfClass:[MyClass class]] && defaultInstance != nil)
  {
    [self release];
    return defaultInstance;
  }

  return [super init];
}
@end

@implementation MyClass
- (id)init
{
  ivar_ = 12345;

  if ((self = [super init]))
    NSLog(@"ivar_ value is %d", ivar_);

  return self;
}
@end

int main()
{
  NSAutoreleasePool *pool = [NSAutoreleasePool new];

  defaultInstance = nil;
  defaultInstance = [[MyClass alloc] init];
  NSLog(@"%d", defaultInstance->ivar_); // outputs 12345

  defaultInstance->ivar_ = 98765;
  NSLog(@"%d", defaultInstance->ivar_); // outputs 98765

  MyClass *someInstance = [[MyClass alloc] init];
  NSLog(@"%d", someInstance->ivar_); // outputs 98765

  if (someInstance == defaultInstance)
    NSLog(@"They're the same!");

  [pool drain];
  return 0;
}

ivar_ value is 12345
12345
98765
ivar_ value is 98765
98765
They're the same!
+5

All Articles