Reputation: 617
I'm a newbie in Objective-C. I have learned some others programs language before such as C++, C#, Java.In these language, syntax to call attributes or methods are object.attributes, object.methods and in Objective-C are object.attributes, [object methods]. Sometimes I can call [object attributes] in Objective-C but sometimes I can't. When I can use both, I wonder if there are any differences and which is better on these cases. And are we use the syntax [] on cases not the same in Java, C#?
Example: I have a ObjectItem array. ObjectItem is a class have a BOOL-type attribute is isLive. I want to change value of the last item on this array.
Right: ((ObjectItem*)tempListDetail.lastObject).isLive=YES;
Wrong: [((ObjectItem*)tempListDetail.lastObject) isLive]=YES;
and I don't know why it wrong :(
Please tell(explain) me if you know, thanks. Sorry if I have any annoy or mistake :D
Upvotes: 1
Views: 97
Reputation: 13343
Using dot notation allows you to set a property. Calling the method isLive
only returns a value, to set the property you need to call the setter - setIsLive:
Upvotes: 1
Reputation: 726639
The way you call a setter for isLive
using the square bracket syntax is different: you replace the name of the getter (which coincides with the name of the attribute) with the name of the setter, like this:
[((ObjectItem*)tempListDetail.lastObject) setIsLive:YES];
When you use the dot syntax, Objective C compiler performs this little transformation for you, so the code ends up calling the same setter in both cases. There is no "better" or "worse" syntax here - pick one that you like better, and use it consistently throughout your program.
Upvotes: 2