Using extern @class in order to add a category?

2019-07-07 19:39发布

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'.

2条回答
甜甜的少女心
2楼-- · 2019-07-07 19:52

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.

查看更多
老娘就宠你
3楼-- · 2019-07-07 19:55

Yes, that's exactly what the @class directive is for (without the extern part).

查看更多
登录 后发表回答