I am new in ios development. I want to know the difference between:
[object1 method];
object1.method;
I know it's the same thing but i still have confusion.
Thank you for help.
I am new in ios development. I want to know the difference between:
[object1 method];
object1.method;
I know it's the same thing but i still have confusion.
Thank you for help.
It is a bit confusing. In theory (at least according to some "authorities") the second form should only be used for properties, not regular declared methods. In practice the compiler doesn't appear to care.
But of course note that the second form can also be used as an assignment target (rather than a value source) -- object1.method = value2;
. In this case the code is translated to [object1 setMethod:value2];
.
The second form is purely "syntactic sugar" that generates the exact same code as the bracket form.
The code
object.property
invokes the method
[object property]
(a getter)
and
object.property = value;
invokes the code
[object setProperty: value];
As others have pointed out, it is considered bad form to use dot syntax EXCEPT to invoke a property's getter/setter, but it does work.
Some language purists frown on the dot notation, saying that it's syntactically ambiguous
(the expression foo.bar
could mean that foo
is an object and bar
is a property of that object,or foo
could be a C struct, and bar
could be a field of the struct. From that bit of code you can't tell which it is. You have to go look at the declaration of foo to tell the difference.)
I see the purist's point, but love the dot notation all the same. It's sooo much simpler to type, and to parse as well. It's easy to lose track of the bracket nesting in complex expressions using properties of properties. Dot notation makes it easier to follow the gist of the expression, and also makes it more succinct.
Technically you can use dot notation for methods, although you shouldn't. Dot syntax is intended to use only when working with properties. For methods, use regular message syntax ([object selector];
)
If you scroll down to the "Methods and Messaging" section of the following documentation link from apple, you'll see that it doesn't matter. You can send messages using square brackets or dot notation. This applies to properties or calling methods. The compiler converts the dot notation to square brackets whenever you build your app, so the code is exactly the same at runtime either way.