Thursday, 15 July 2010

class - objective-c instance variables -



class - objective-c instance variables -

there question couple years re instance vs class methods. illustrated code below. understand part, except why need both instance variable "age" , instance method "age"?

won't getter , setter instance variable "age" created @synthetize?

static int numberofpeople = 0; @interface mnperson : nsobject { int age; //instance variable } + (int)population; //class method. returns how many people have been made. - (id)init; //instance. constructs object, increments numberofpeople one. - (int)age; //instance. returns person age @end @implementation mnperson - (id)init{ if (self = [super init]){ numberofpeople++; age = 0; } homecoming self; } + (int)population{ homecoming numberofpeople; } - (int)age{ homecoming age; } @end main.m: mnperson *micmoo = [[mnperson alloc] init]; mnperson *jon = [[mnperson alloc] init]; nslog(@"age: %d",[micmoo age]); nslog(@"%number of people: %d",[mnperson population]);

(original code @micmoo)

the instance method age encapsulation. lets subclasses override method, providing different implementation if need to. example, subclass may want calculate age based on initial date , current date, rather storing it. if utilize instance variable, subclasses have no alternative override age; if add together instance method, subclasses able provide new implementation.

another advantage cannot write age: users of class can age, cannot set it.

won't getter , setter instance variable "age" created @synthetize?

the @synthesize requires property declaration, missing class. properties relatively new language, may explain reason why not used in code found.

the current way of doing same thing declaring property instead of ivar , accessor, , skipping @synthesize altogether:

@property (nonatomic, readonly) int age;

you can write age within class assigning _age, backing variable created automatically; users can read value using either [obj age] or obj.age syntax.

objective-c class variables methods instance

No comments:

Post a Comment