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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…