What's the difference between dot syntax and square bracket syntax?

后端 未结 5 491
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 06:27

I am going through some walkthroughs fpr Objective-C and I got to many places where I raised my eyebrows. I would love to get them down.

  1. Is there a fundamen

5条回答
  •  萌比男神i
    2020-11-27 07:07

    I'm not sure what kind of distinction you're trying to make between "message sending" and "method calling", since they're two ways of describing the same thing. The dot syntax is just a shortcut for calling getters and setters, that is:

    [foo length]
    foo.length
    

    are exactly the same, as are:

    [foo setLength:5]
    foo.length = 5
    

    You should generally only use the dot syntax when you're using getters and setters; use the square bracket syntax for all of your other method calls.

    For your second question: this is how dynamic typing works. Any type declarations you put in your code are hints to the compiler; your Objective-C method calls will always work as long as the objects respond to them.

提交回复
热议问题