I'm currently learning objective-c. What exactly do the square braces around things signify and is there any difference between using that and using a period (I'm from a .NET world so this would be simpler for me).
Thanks.
I'm currently learning objective-c. What exactly do the square braces around things signify and is there any difference between using that and using a period (I'm from a .NET world so this would be simpler for me).
Thanks.
They both do the same thing in your example. The .
is a sort of shorthand used to access a property of an object. []
are used to send a message to the object. In your example, those happen to be the same thing. You'll notice the difference if you try to send a message that doesn't directly map to a property name.
For example: [myString length]
and myString.length
are the same, but if you wanted to set the length (let's assume that makes sense for the example's sake), you'd need to do something like [myString setLength:newLength]
or myString.length = newLength
. Besides that, there are messages that aren't the same as property names - like this example:
[myString stringByReplacingOccurrencesOfString:@"hello" withString:@"world"];
which has no meaningful equivalent using the .
shorthand.
Objective-C uses messages, rather than methods, and that's the main syntax (the dot syntax was introduced as an alternative for simple get/set messages). There are obviously significant similarities between methods and messages, but also differences.
In Objective-C, objects have complete flexibility in responding to a message at runtime. They can handle a totally unexpected message, for instance by proxying it to another object. Or, you could do things like map messages to columns at runtime. This is based on a legacy going back to Smalltalk.
.NET only just got this flexibility with dynamic
/DynamicObject
/IDynamicMetaObjectProvider
. Of course, in either language, method/message names defined at compile-time are usually more appropriate. But there are notable use cases for dynamic ones.
Of course, Objective-C is a superset of C, so the .
is used for other things (generally structs or unions).