Dedicated Initializer in Objective-C -
i newbie objective-c. have 'xyzperson' class attributes {firstname, lastname, dateofbirth} , want when write "xyzperson *person=[[xyzperson alloc] init]" in main, should call overridden 'init' method should in-turn call designated initializer , initializes object defined values.
my code snippets. http://pastebin.com/ffxnddhf
#import <foundation/foundation.h> #import "xyzshoutingperson.h" int main(int argc, const char * argv[]) { @autoreleasepool { xyzperson *person=[[xyzperson alloc] init]; if(person) { [person sayhello]; } else { nslog(@"person object null"); } } return 0; } -(id)init { self=[super init]; return [self initwithfirstname:@"ankit" lastname:@"sehra" dob:01/01/2000]; } -(id)initwithfirstname:(nsstring *)afirstname lastname:(nsstring *)alastname dob:(nsdate *)adateofbirth { _firstname=afirstname; _lastname=alastname; _dateofbirth=adateofbirth; } -(void)sayhello; { nslog(@"%@ %@ %@",self.firstname,self.lastname,self.dateofbirth); }
write output of program "person object null", want print firstname, lastname , dob.
if class has several init methods, 1 of them "designated initializer". 1 calls [super initxxx]
. in example, initwithfirstname:lastname:dob:
designated initializer , should this:
-(id)initwithfirstname:(nsstring *)afirstname lastname:(nsstring *)alastname dob:(nsstring *)adateofbirth { self = [super init]; if (self) { _firstname=afirstname; _lastname=alastname; _dateofbirth=adateofbirth; } return self; }
(i have changed type of dateofbirth
property , dob
argument nsstring
, explain later.)
all other init methods call designated initializer (and not [super initxxx]
), in example init
:
-(id)init { return [self initwithfirstname:@"ankit" lastname:@"sehra" dob:@"01/01/2000"]; }
note (among several other errors), "01/01/2000" not nsdate
,
return [self initwithfirstname:@"ankit" lastname:@"sehra" dob:01/01/2000];
does not make sense. therefore, first working example you, have changed argument type nsstring
.
Comments
Post a Comment