문제

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top