Note, I'm specifically referring to the fact that dot notation is being used with class methods, not instance methods.
Out of curiosity, I wanted to see what would happen if I tried to use Objective-C dot notation syntax with a class method. My experiment was as follows:
#import <Foundation/Foundation.h>
static int _value = 8;
@interface Test : NSObject
+ (int) value;
+ (void) setValue:(int)value;
@end
@implementation Test
+ (int) value {
return _value;
}
+ (void) setValue:(int)value {
_value = value;
}
@end
int main(int argc, char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Test.value: %d", Test.value);
NSLog(@"[Test value]: %d", [Test value]);
Test.value = 20;
NSLog(@"Test.value: %d", Test.value);
NSLog(@"[Test value]: %d", [Test value]);
[Test setValue:30];
NSLog(@"Test.value: %d", Test.value);
NSLog(@"[Test value]: %d", [Test value]);
[pool release];
return 0;
}
I was surprised to see that this was compiled, let alone executed with what is, I suppose, correct behavior. Is this documented somewhere, or just a fluke of the compiler?
I compiled using GCC on Mac OS X 10.6:
gcc --version: i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659)
compile using: gcc ObjCClassDotSyntax.m -framework Foundation -o ObjCClassDotSyntax
run: ./ObjCClassDotSyntax
output:
2010-03-03 17:33:07.342 test[33368:903] Test.value: 8
2010-03-03 17:33:07.346 test[33368:903] [Test value]: 8
2010-03-03 17:33:07.351 test[33368:903] Test.value: 20
2010-03-03 17:33:07.352 test[33368:903] [Test value]: 20
2010-03-03 17:33:07.353 test[33368:903] Test.value: 30
2010-03-03 17:33:07.353 test[33368:903] [Test value]: 30
Calling a method While creating a Objective-C method, you give a definition of what the function has to do. To use a method, you will have to call that function to perform the defined task. When a program calls a function, program control is transferred to the called method.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console. log(cat.name);
This is correct behavior. foo.method
is syntactic sugar for [foo method]
—a straight conversion with identical semantics. Similarly foo.prop = bar
is syntactic sugar for [foo setProp:bar]
, again with identical semantics. This transformation is implemented in the compiler. Thus you can use dot notation to call 0-parameter methods as in foo.doSomething
instead of [foo doSomething]
. Of course, if you do this, you are evil.
The fact that the callee is a class instance doesn't mater because in Objective-C, classes are also objects. Using dot notation on a class calls the parameterless method on that class.
Dot notation is described in the Objective-C Programming Language document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With