ios - Creating Initializers in Objective-C -


the previous instructions in book reading create designated initializer bnritem class, book walked me through:

bnritem.h  // designated initializer bnritem - (instancetype)initwithitemname:(nsstring *)name                   valueindollars:(int)value                     serialnumber:(nsstring *)snumber;   bnritem.m  - (instancetype)initwithitemname:(nsstring *)name                   valueindollars:(int)value                     serialnumber:(nsstring *)snumber {     // call superclass's designated initializer     self = [super init];      // did superclass's designated initializer succeed?     if (self) {         // give instance variables initial values         _itemname = name;         _serialnumber = snumber;         _valueindollars = value;          // set _datecreated current date , time         _datecreated = [[nsdate alloc] init];     }     // return address of newly created initialized object     return self; } 

the book explained init method gets inherited brnitem's superclass , how override method:

bnritem.h  -(instancetype)init {     return [self initwithitemname:@""]; } 

now, completing challenge @ end of chapter , have feeling making more complicated needs be. challenge reads:

silver challenge: initializer

"create initializer method bnritem class. initializer not designated initializer of bnritem. takes instance of nsstring identifies itemname of item , instance of nsstring identifies serialnumber."

excerpt from: joe conway. “ios programming.” ibooks. https://itun.es/us/zni-w.l

below code have created:

bnritem.h  // initializer - (instancetype)initwithitemname:(nsstring *)name                     serialnumber:(nsstring *)snumber;   bnritem.m  - (instancetype)initwithitemname:(nsstring *)name                     serialnumber:(nsstring *)snumber {     return [self initwithitemname:name                      serialnumber:@""]; 

is solution correct?

we nominate designated initializer extend super-class, , other intializers call designated initializer. purpose of designated initializer is:

  • to ensure class in after creation.
  • avoid duplicating code. have 1 intializer performing config, , others invoke 1 passing parameters.

if makes sense can have designated initializer private (by removing header) , expose simpler initializers. eg when of parameters might nil, rather have user guess if valid or not, can provide initializer parameters usage.

all of non-designated initializers call designated initializer. designated initializer should expose configurable parameters cases.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -