Lesson 3 Adding functionality to a Class: Methods and Messages

Master how to write and call methods in OC. Build a functional game.



1.Method Definition Syntax & Calling Methods

-(returnType)methodName: (parameterType*)firstParameter
            moMethodName:(parametherType*)secondParameter {
    body;
}
  • In OC, instead of saying we're calling a method, we say that we're sending a message. Object message send is not called until runtime. consequently the relationship between the message and the receiver is not resolved until runtime.
  • 這正好與Swift中的調(diào)用相反。
  • In Swift, a function call binds a particular implementation of a method to a particular instance of a type at compile time.
[receiver message: argument];
[[RPSTurn alloc] initWithMove: playersMove];

Sending a message to nil in OC is A-OK.(not method)
Just like we saw with properties, in order for a method to be visible outside of its class, it must be included in the header file.


2.Switch in OC

Switch statements in OC are quite limited compared to Swift, they can only condition upon the value of an integer.

switch (integer) {
    case 0:
        statement;
        break;
    case 1:
        statememt;
        break;
    default:
        statement;
        break 
}
  • 每一個case后面都要有break語句
switch (randomNumber) {
    case 0:
        return Rock;
        break;
    case 1:
        return Paper;
        break;
    case 2:
        return Scissors;
    default:
        return Invalid;
        break
}

3.if statement in OC

if (condition) {
    statements;
} else {
    statemetns;
}

Quiz: What is the principal difference between a function call and a message? How does messaging work in OC?

  • The principal difference between a function call and a message is that a function and a particular method implementation are coupled at compile time, but a message and its receiver are not linked until runtime. At runtime a call to the NSObject method, objc_msgSend(), makes a connection between receiver and message.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容