使用extern @class为了添加类别? [英] Using extern @class in order to add a category?

查看:203
本文介绍了使用extern @class为了添加类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法承诺一个类存在于其他地方(即类似于 extern keyword ),因此避免使用 #import 语句?



我想做什么:

  extern @class MyClass; 

@interface Foo:NSObject
@property(nonatomic)MyClass * abc;
@end

其中 MyClass 肯定存在并且在我的程序中使用,但是在我创建这个文件的时候,我不知道定义 MyClass 的文件的名称。



更新:似乎这个错误与这是一个类别有关。更新代码如下:

  @class MyClass; 

@interface MyClass(Extensions)
- (void)foo;
@end

出现以下错误:


无法为未定义类'MyClass'定义类别。



解决方案

您可以通过简单的操作转发声明一个类:

  @class MyClass; 

当你实际使用类时,你仍然需要导入头。 p>

但是,当子类化或为类添加类别时,必须使用导入。编译器必须能够看到真正的类才能修改或扩展它。



你只能选择扩展一个你不能直接导入的类一个文件将是在运行时使用objective-c运行时库来修改类。您可以创建另一个类,然后在运行时将该类的方法添加到实际类中。



基本上,您将使用NSClassFromString获取类,然后使用 class_addMethod 将这些方法添加到真实类中。



这对于你想做的任何事情来说都是过度的。


Is there a way to "promise that a class exists elsewhere" (i.e. similar to the extern keyword) and therefore avoid having to use #import statements?

Here is an example of what I am trying to do:

extern @class MyClass;

@interface Foo : NSObject
@property (nonatomic) MyClass *abc;
@end

Where MyClass definitely exists and is used throughout my program, but at the time I create this file, I don't know the name of the file where MyClass is defined.

Update: It seems like the error is related to the fact that this is a category. Updated code follows:

@class MyClass;

@interface MyClass (Extensions)
- (void)foo;
@end

Gives the following error:

Cannot define category for undefined class 'MyClass'.

解决方案

You can "forward declare" a class by simply doing:

@class MyClass;

When you actually go to use the class though, you will still need to import the header.

However, you must use an import when subclassing or adding a category for the class. The compiler must be able to see the real class in order to modify or extend it.

Your only option to "extend" a class that you can't import directly into a file would be to modify the class at runtime using the objective-c runtime library. You could create another class and then add the methods from that class to the real class at runtime.

Basically you would use NSClassFromString to get the class and then use class_addMethod to add those methods to the real class.

This is almost certainly overkill for anything you would want to do though.

这篇关于使用extern @class为了添加类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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