2

If I want to know the size of a NSArray, there are two similar methods I can use like:

NSArray *arr = @[@"1", @"2"];
NSInteger i = [arr count];
NSInteger j = arr.count;

So what the difference between these two methods? Will there be any performance difference or else? Thanks a lot

billyho
  • 141
  • 1
  • 7
  • possible duplicate of [Dot Notation vs Method Notation](http://stackoverflow.com/questions/11386256/dot-notation-vs-method-notation) – Sulthan Aug 07 '14 at 06:41
  • See these links to know more about this http://stackoverflow.com/questions/7423853/whats-the-difference-between-dot-syntax-and-square-bracket-syntax and http://stackoverflow.com/questions/11474284/what-is-preferred-in-objective-c-dot-notation-or-square-bracket-notation – Yogendra Aug 07 '14 at 06:45
  • they are basically the same thing here, both call the _getter_ of the `count` property. – holex Aug 07 '14 at 14:37

3 Answers3

1

With [arr count]; you send the message count to the array object.

If arr.count comes to the right of some expression, you are calling the getter of the count property, which is basically the same as [arr count];

If object.someProperty comes to the left of some expression, you are calling the setter of the count property, which is basically the same as [object setSomeProperty:someValue].

Because the syntax of the getter and the sending a message to an object represent the same thing for a property (when on right side of an expression), the compiler allows you to use the . (dot) syntax even if the name of what comes right after the dot is not necessarily a getter of a property (for example count is a method of the NSArray class, but compiler does not complain if you use [arr count] or arr.count).

ppalancica
  • 4,236
  • 4
  • 27
  • 42
  • The last paragraph of your answer doesn't make any sense and isn't correct. Setters and getters are methods on the object that you can call (sending message with). The dotted references are shorthands for sending messages. The arr.count is either [arr setCount] or [arr count] depending pn whether the reference is on the left hand side of the expression or appears on the right hand side of the expression. – Sunny Aug 07 '14 at 08:03
1

[arr count] and arr.count are basically the same thing. Both call obj_msg_send, the dot syntax is just syntatic sugar for [arr count].

snod
  • 2,442
  • 3
  • 20
  • 22
-1

[arr count] when you call this you are straight away accessing the getter method.

arr.count when you use .(dot) you are accessing the property of an object but value wise both gives same count.

Rajesh
  • 10,318
  • 16
  • 44
  • 64