2011年2月8日 星期二

[Objective-C] Classes 筆記 (2) - Method, Message Sending 方法與訊息傳遞

Methods
  1. instance method (宣告時在開頭用 - )
  2. class method (宣告時在開頭用 + )
    • 用法像是JAVA的static method
差別在於instance method要先實例化, class method可以直接透過Object使用
-(void) instanceMethod:(NSString *)param;
+(void) classMethod:(NSString *)param;


Message Sending -- 訊息傳遞

[object method:param];

有點類似其他語言的call function or call method, 但是嚴格上來說是不一樣的
object.methodName(params);

Message Sending即使你打錯method name或是method不存在的時候, compiler並不會顯示錯誤, 因為object會自動忽略, 在XCode上, 只會出現警告訊息, 'Object' may not respond to '-method'



  • MyClass.h
#import <Foundation/Foundation.h>

@interface MyClass : NSObject {
}

//--instance methods--
-(void) doSomething;
-(void) doSomething:(NSString *)str;
-(void) doSomething:(NSString *)str withParam:(float)value;

//--class method-- 
+(void) alsoDoSomething;

@end

  • MyClass.m
#import "MyClass.h"

@implementation MyClass

-(void) doSomething {
}

-(void) doSomething:(NSString *)str {
}

-(void) doSomething:(NSStrgin *)str withParam:(float)value {
}

@end

import MyClass來使用

  • Main.m
#import "MyClass.h"

#implementation

-(void) main {
    // instance method
    MyClass *myClass = [MyClass alloc];
    [myClass doSomething];
    [myClass doSomething:@"String"];
    [myClass doSomething:@"String" withParam:6.0f];

    // class method
    [MyClass alsoDoSomething];
}

@end


Nested Message -- 使用return的值當另一個method的參數值

在其他語言可能長這樣
function1 ( function2() );

Objective-C
[Object method1:[object method2]]; 


Reference

Beginning-iOS-4-Application-Development
The Objective-C Programming Language: Defining a Class
Related Posts Plugin for WordPress, Blogger...