加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 使用的点是什么[self class]

发布时间:2020-12-15 01:53:15 所属栏目:百科 来源:网络整理
导读:这段代码是否正确 @implementation Vehicle+(id) vehicleWithColor:(NSColor*)color { id newInstance = [[[self class] alloc] init]; // PERFECT,the class is // dynamically identified [newInstance setColor:color]; return [newInstance autorelease]
这段代码是否正确

@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 class]在一个类方法中是不必要的(在Objective-C而不是“static”方法中更常见),因为self已经是一个类,并且[self class]返回自身。

但它有点更有趣。在Objective-C中,类对象在技术上是元类的实例。所以在类方法中的[self class]应该返回元类而不是类本身。但是为了实际的目的,Objective-C隐藏了元类,因此特别处理这种情况。

关于这个话题的一些很好的阅读:

> http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
>继承图:http://www.sealiesoftware.com/blog/class%20diagram.pdf
> http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读