使用[自课]有什么意义
这段代码正确吗
@implementation Vehicle
+(id) vehicleWithColor:(NSColor*)color {
id newInstance = [[[self class] alloc] init]; // PERFECT, the class is // dynamically identified
[newInstance setColor:color];
return [newInstance autorelease];
}
@end
为什么使用 [self class]
我认为 self 已经指向静态方法上的类(带有 + 的类)
Is this code correct
@implementation Vehicle
+(id) vehicleWithColor:(NSColor*)color {
id newInstance = [[[self class] alloc] init]; // PERFECT, the class is // dynamically identified
[newInstance setColor:color];
return [newInstance autorelease];
}
@end
Why use [self class]
I thought self already points to the class on static methods (the ones with +)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的:
[self class]
在类方法中是不必要的(在 Objective-C 中更常被称为而不是“静态”方法),因为self
是已经是一个类,并且[self class]
返回自身。但它变得更有趣了。在 Objective-C 中,类对象在技术上是元类的实例。因此,类方法中的
[self class]
应该返回元类而不是类本身。但出于实际目的,Objective-C 隐藏了元类,因此它专门处理这种情况。关于此主题的一些好读物:
You're right:
[self class]
is unnecessary in a class method (it's more commonly called that in Objective-C rather than "static" method), becauseself
is already a class, and[self class]
returns itself.But it gets a bit more interesting. In Objective-C, class objects are technically instances of metaclasses. So
[self class]
in a class method ought to return the metaclass instead of the class itself. But for practical purposes, Objective-C hides the metaclass so it handles this case specially.Some good reading on this topic:
它是为了支持子类化。如果您对类名进行硬编码,如
[[Vehicle alloc] init]
中所示,则 Vehicle 的子类必须重写 +vehicleWithColor: 才能使其执行正确的操作。使用[self class]
,您可以创建一个 HarleyDavidson 子类,并且[HarleyDavidsonvehicleWithColor:[NSColor blackColor]]
会自动执行正确的操作,而是创建 HarleyDavidson 的实例Vehicle 实例的。(编辑:)
请参阅下面 Joe 关于类方法中的
self
与[self class]
的评论 - 在类方法中,它不会使一个区别。但在某种情况下它可以。类可以响应根类中定义的实例方法 --class
本身就是这样一个方法,在 NSObject 协议中定义为实例方法。因此,如果您通过添加实例方法来扩展根类(例如 NSObject),则该方法如果需要引用其自己的 Class 对象,则应始终使用[self class]
。It's to support subclassing. If you hard-coded the class name, as in
[[Vehicle alloc] init]
, then a subclass of Vehicle would have to override +vehicleWithColor: to make it do the right thing. With[self class]
, you could create a subclass HarleyDavidson, and[HarleyDavidson vehicleWithColor:[NSColor blackColor]]
would do the right thing automatically, creating an instance of HarleyDavidson instead of an instance of Vehicle.(Edit:)
See Joe's comment below concerning
self
vs.[self class]
in class methods - In class methods, it doesn't make a difference. But there is a situation where it can. Classes can respond to instance methods that are defined in a root class --class
itself is just such a method, defined as an instance method in the NSObject protocol. So if you extend a root class such as (for example) NSObject by adding an instance method, that method should always use[self class]
if it needs to refer to its own Class object.