在共享的objective-c方法中获取类类型? [英] Get class type in shared objective-c method?

查看:108
本文介绍了在共享的objective-c方法中获取类类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中有Alloc / Init隐喻。他们还添加了一种称为 new的共享便捷方法,该方法在内部仅连续调用这两种方法。而且,如果我创建了一个名为FooClass的NSObject子类,FooClass将选择那些共享方法,包括'new'。

In Objective-C there is the Alloc/Init metaphor. They've also added a shared convenience method called 'new' that internally just calls both in succession. And if I create a subclass of NSObject called FooClass, FooClass picks up those shared methods, including 'new'.

但是...到底是怎么实现的?

BUT... how the heck is that implemented??

它不能简单地委托给基类,因为那只会实例化NSObject的实例,而不是您的派生类FooClass,但它仍然可以工作!那么有人会怎么写类似的东西呢?

It can't simply delegate to the base class because that would just instantiate an instance of NSObject, not your derived class FooClass, yet it still works! So how would someone write something similar?

换句话说,基类不应该是这个...

In other words, the base class shouldn't be this...

  + (id) somethingLikeNew{
        return [[NSObject alloc] init];  
    }

但是,这...

  + (id) somethingLikeNew{
        return [[<SomethingThatMapsToFooClassType> alloc] init];  
    }

...其中'SomethingThatMapsToFooClassType'是继承的派生类的类型

...where 'SomethingThatMapsToFooClassType' is the type of the derived class that inherits from NSObject and which needs to pick up the shared method 'somethingLikeNew'.

基本上我要添加NSObject的类别,并且我有一些共享方法需要了解类型,但实现都是通用的,因此会在NSObject上使用类别,而不是在我的类文件中全部使用(以相同的方式,您不必在整个地方使用 new。就在那儿。)

Basically I'm adding a category off of NSObject and I have shared methods that need to know the type, but the implementations are all generic, hence going in a category on NSObject and not all over the place in my class files (the same way you don't have 'new' all over the place. It's just there.)

有人吗?布勒? bueller?

Anyone? Bueller? Bueller?

M

推荐答案

在任何Objective-C方法中, self (隐式)参数是指接收者。对于类方法, self Class 对象。因此可以实现多态类方法,例如

Within any Objective-C method, the self (implicit) parameter refers to the receiver. In the case of a class method, self is the Class object. So polymorphic class methods can be implemented like

+ (id)somethingLikeNew
{
   return [[self alloc] init];
}

这篇关于在共享的objective-c方法中获取类类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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