2009年2月9日 星期一

class:interface, implementation, inheritance, accessor, @property, dot

class declaration:
ex:
@interface Student : NSObject
{
int age;
}
- (void) setAge: (int) age;
- (void) speak;
@end

note:
1.if a method has argument, its name has a colon
2. inheritance:
a. use : , NSObject is super class of Student
b. not support multiple inheritance
3. isa:
instance varabile of NSObject, a pointer to the object's class
ex:
Shape *s = [Circle new];
NSLog(@"isa %@", s->isa);
---> Circle
4: super
call parent class's method definition
ex:
[super speak];

class definition:
@implementation Student
- (void) setAge: (int) a
{
age = a;
}

- (void) speak
{
NSLog(@"speak");
}

@end

note: if parameter uses the same name as instance variable,
use self to distinguish instance variable and parameter
ex:
self->name & name

accessor:
instance variable is protected, can access directly, but usually access from method
ex:
Circle *a = [Circle new];
NSLog(@"name %s", a->name);
id b = [Circle new];
NSLog(@"name %s", ((Circle*)b)->name);
note:
if the variable is with type of parent class,
it will not know instance variable defined in child class
Hence, must use cast
However, call method does not need to cast
the object will find suitable method automatically

name convention for accessor:
getter name conventions:
the same as instance variable name
setter name conventions:
add set before instance variable name
ex:
setAge

new accessor method: @property & @synthesize
create accessor for you
ex:
@interface People {
int age;
}
@property int age;
@end

@implementation People
@synthesize age;
@end

dot:
you can use dot to access instance variable
ex:
peter.age


沒有留言:

張貼留言