请注意,我特别指的是使用点表示法来调用类方法,而不是实例方法。
出于好奇,我想尝试使用 Objective-C 的点表示法语法来调用类方法。我的实验如下:
#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;
}
看到这段代码被编译并以我认为是正确的行为执行,我感到惊讶。这个现象有文档记录吗?还是只是编译器的偶然事件?
我在Mac OS X 10.6上使用GCC编译:
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
foo.prop
纯粹转换为[foo prop]
,那么 Xcode 不应区分类方法和实例方法。 - Timo