【发布时间】:2012-03-12 05:14:05
【问题描述】:
在 Objective C 编程中,4e,第 9 章,程序 9.3:
#import "Square.h"
int main (int argc, char * argv[])
{
@autoreleasepool {
Square *mySquare = [[Square alloc] init];
...
// respondsTo:
if ( [mySquare respondsToSelector: @selector (setSide:)] == YES )
NSLog (@"mySquare responds to setSide: method");
...
if ( [Square respondsToSelector: @selector (alloc)] == YES )
NSLog (@"Square class responds to alloc method");
...
}
return 0;
}
第一季度:
既然-respondsToSelector:是实例方法,不是类方法,那为什么可以直接在Square类上使用呢?
第二季度:
书上说你可以在这里使用Square 而不是[Square class]。它只是一个特殊的捷径,还是这背后有什么机制?
任何帮助将不胜感激!提前致谢!
【问题讨论】:
-
1.简短的回答是因为归根结底,它们都是选择器。 2. Square(大写)已经是一个类,
class方法字面上返回的是同一个对象。 -
Q2:
Square求值为 Square 的元类,它是一个表示 Square 类的对象。它是一个对象实例,因此您可以向它发送消息。将+class发送到元类对象,返回自身。 -
实际上,我上面的评论回答了你的两个问题:)
-
@CodaFi:感谢您的快速回复!但是,实例方法(例如
-respondsToSelector:)不应该只用于实例对象吗? -
好吧,你必须了解选择器是什么。无论是类方法还是实例方法,所有选择器都是 SEL 类型,这是该方法采用的参数之一。它只是检查您提供的 CLASS 是否响应它。无论如何,类方法都可以在实例方法中调用,所以这一点没有实际意义。
标签: objective-c class class-method instance-methods respondstoselector