2008年2月24日 星期日

objective-c syntax

use import to include header file

define class:
@interface Dog: NSObject {
int head;
}
-(void) print: (int) d;
@end;

(1) Dog extends NSObject, @interface = Java's class
(2) instance variables are defined between { }
(3) default access is protected
(4) method's syntax: - (return type) name: (parameter1 type) parameter;
- means instance method, static method(class method) uses +

how to access public instance variable
ex: ceo object has instance variable boss,
ceo -> boss

how to define method with multiple parameters:
ex: -(void) eat: (int) n andDrink: (int) d;
andDrink is label name. It is optional, but is recommended

how to call method:
[object method], ex: [dog eat] = dog->method in Java
objective-c does not have value type. It is always pointer type. Hence, [dog eat] = dog->method, not dog.method

how to call method with parameters
ex: (1)[dog eat: 1 :2]
1 and 2 are the parameters
(2) [dog eat: 1 drink:2]
1 and 2 are the parameters
alloc and init method:
alloc: allocate memory, ex: [Dog alloc]
init: initialize variable in the object
Use alloc and init to create new object: ex: Dog *dog = [[Dog alloc] init];

how to define constructor :
call "self = [super init];" in the constructor definition
self is like "this" in Java, super means parent, call parent's init method to init object

nil:
nil = NULL in C

access privileges:
ex:
@public
int a;
@private
int b;
@protected
int c

id:
a type, a general pointer to an object, the type of object is determined at runtime

self and super:
self = this in Java
super = super in Java

沒有留言: