使用类方法的Objective-C点表示法? [英] Objective-C dot notation with class methods?

查看:115
本文介绍了使用类方法的Objective-C点表示法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意,我是专门指的是点表示法与类方法一起使用,而不是实例方法.

出于好奇,我想看看如果尝试对类方法使用Objective-C点表示法语法会发生什么.我的实验如下:

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;
}

我很惊讶地看到它已被编译,更不用说以正确的行为执行了.是在某处记录了该文件,还是只是编译器的fl幸记录?

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?

我在Mac OS X 10.6上使用GCC进行了编译:

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

推荐答案

这是正确的行为. foo.method[foo method]的语法糖,具有相同语义的直接转换.类似地,foo.prop = bar[foo setProp:bar]的语法糖,同样具有相同的语义.此转换是在编译器中实现的.因此,您可以 使用点表示法来调用0参数方法,就像在foo.doSomething中一样,而不是在[foo doSomething]中.当然,如果这样做,您将邪恶.

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.

被调用方是类实例这一事实并不重要,因为在Objective-C中,类也是对象.在类上使用点符号会在该类上调用无参数方法.

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.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆