2012年6月26日 星期二

class and instance method


Class Method

Starts with a plus sign
+ (id) alloc;
+ (Ship *)motherShip;
   + (NSString *)stringWithFormat:...
+(void) doSomething;

Creation & Utility Methods
Calling syntax
   [Class method]
   Ship *ship = [Ship motherShip];
   NSString *resultString = [NSString stringWithFormat:@“%g”, result];
   [[ship class] doSomething];// 呼叫方法



self/super is this class

self means “this class’s class methods”

super means “this class’s superclass’s class methods”


在使用上,self與super都是 class,因此呼叫的都是class的method
self只是一個pointer指向你自己。


甚麼時候使用class method

1. 創建 instance/object

2. share instance

3. get information from class



class是沒有類似instance的屬性及變數。


Instance method


Starts with a dash (-)
- (BOOL)dropBomb:(Bomb *)bomb
              at:(CGPoint)position
            from:(double)altitude;

“Normal” Instance Methods
Calling syntax
[<pointer to instance> method]
Ship *ship = ...; // instance of a Ship
destroyed = [ship dropBomb:firecracker
                               at:dropPoint
                                from:300.0];

self/super is calling instance
self means “my implementation”
super means “my superclass’s implementation”

[self greeting]; // 呼叫方法, 在同一檔案內, xcode的標準寫法

與 Class Method 的差別,在於
號,代表這是一個 Instance Method
其他則與 Class Method 相同。

另外,要使用 Instance Method必須先產生 Instance / Object (實體 / 物件)

實體呼應instance method
- (id) init;  // e.g. [[Hello alloc ] init ]  <---需要初始設定
- (void) greeting:(NSString *) word;

類別呼應class method
+ (id) alloc;   // e.g. [Hello alloc]
+ imageNamed:(UIImage) image;
// [UIImage imageNamed:@”hello.png”] 




Example 

image

image




@interface Vehicle  // Class  
- (void)move;
@end

@interface Ship : Vehicle  // class  inherit
- (void)shoot;
@end

Ship *s = [[Ship alloc] init];
[s shoot];
[s move];

沒有留言: