Objective-C Multiple Initialisers

帅比萌擦擦* 提交于 2019-12-04 23:04:12

The designated initializer's definition is here. It is a strong requirement to ensure that your instances are consistent whatever the initializer you use. For a full reference, see the Objective-C Programming Guide: the initializer implementation is well documented.

Edit 2: Fix typo reported by @NSResponder

Edit:

I think calling init after setting the member is not reliable. Members may have weird values that will fail the test for initialization.

A better way to do it is to call the "init" method first (which will set default values for members) and then to set the member. This way, you have the same code structure for all your initializers:

- (id) init {
    self = [super init];
    if(self){
        self.userID = 0;
        self.userName = nil;
        self.emailAddress = nil;
    }
    return self;
}

- (id) initWithUserID:(NSInteger) candidate {
    self = [self init];
    if(self){
        self.userID = candidate;
    }
    return self;
}

The way I tend to do this kind of thing is for the designated initializer to be the method that takes the most parameters, and the simpler initializers just send the more detailed -init messages. For example:

   // simple initializer
- (id) init
  {
  return [self initWithWidth: 1.0];
  }

  // not so simple initializer
- (id) initWithWidth:(float) aWidth
  {
  return [self initWithWidth:aWidth andColor:nil];
  }

  // designated initializer.  This is the one that subclasses should override.
- (id) initWithWidth: (float) aWidth andColor: (NSColor *) aColor 
  {
  if (self = [super init])
   {
   self.width = aWidth;
   self.color = aColor ? aColor : [[self class] defaultColor];
   }
  return self;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!