0

Can someone explain to me why in Objective C when declaring a string with

NSString *string;

I can use both string.length and [string length] to return the length of the string?

in the .h there is only the method

-(NSUInteger *)length

So why can I use the (dot) notation?

Cyrille
  • 25,014
  • 12
  • 67
  • 90

1 Answers1

2

It's just syntactic sugar, they are both the same. Dot notation came in with @property but behind the scenes it's converted into method calls for you. Indeed, any @property Definition you do have will generate associated accessor methods and they are what is actually called. Again, you can call the method names rather than using dot notation.

Try to use the notation which makes the most sense, both to you and for the context. Dot notation can't be used with methods that take any parameters, but also only use it for methods without side effects.

Interesting article on the topic at the big nerd ranch.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • Oh!!!! of curse !!! thanks for reminding me!!!!! .. why is not present the @property in NSString.h file? – user3315609 Feb 16 '14 at 09:38
  • You'd need to ask Apple, but I'd say it's because there is effectively zero value in refactoring old classes to add properties for simple methods that already work just fine. – Wain Feb 16 '14 at 09:42
  • 1
    @user3315609 @property is not present in NSString.h because it is not a property :) Seeming distracting at first glance, this is true. Dot-syntax is just very-high-level syntactic sugar that allows you to write `NSArray.alloc.init`, although neither of `alloc` / `init` aren't properties. Same with `setX:`. – user3125367 Feb 16 '14 at 09:51
  • http://stackoverflow.com/questions/1249392/style-dot-notation-vs-message-notation-in-objective-c-2-0 – user3315609 Feb 16 '14 at 10:08