美文网首页
Lesson 3 Adding functionality to

Lesson 3 Adding functionality to

作者: 快乐捣蛋鬼 | 来源:发表于2019-08-06 11:57 被阅读0次

    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中的调用相反。
    • 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.

    相关文章

      网友评论

          本文标题:Lesson 3 Adding functionality to

          本文链接:https://www.haomeiwen.com/subject/mpnmdctx.html