objective-c class 扩展方法的前向声明
Forward declaration of objective-c class extension method
以下代码产生错误 No visible @interface for 'Bar' declares the selector 'barMethod' on the second line of implementation of -[Foo fooMethod]
:
// FooBar.m
#import "FooBar.h"
//////////////////////////////////
@implementation Foo
- (void)fooMethod {
Bar *bar = [Bar new];
[bar barMethod]; // Error: No visible @interface for 'Bar' declares the selector 'barMethod'
}
@end
//////////////////////////////////
@interface Bar ()
- (void)barMethod;
@end
@implementation Bar
- (void)barMethod {
// do something
}
@end
除了在 Foo
实现之上移动 Bar
class 扩展之外,是否有任何方法可以在 FooBar.m 中转发声明 -[Bar barMethod]
(这不是很方便有时)?
出于方法可见性的目的,扩展的接口与任何其他接口一样:编译器必须在使用 之前查看声明。*不幸的是,您必须将 @interface
进入 header 或在文件中比 Foo
的实现更靠前。
*我所知道的一个例外是根本没有在接口中命名的方法——基本上由它们的定义声明——并且在同一个 @implementation
块中使用。无论顺序如何,编译器都会为您计算出来。
以下代码产生错误 No visible @interface for 'Bar' declares the selector 'barMethod' on the second line of implementation of -[Foo fooMethod]
:
// FooBar.m
#import "FooBar.h"
//////////////////////////////////
@implementation Foo
- (void)fooMethod {
Bar *bar = [Bar new];
[bar barMethod]; // Error: No visible @interface for 'Bar' declares the selector 'barMethod'
}
@end
//////////////////////////////////
@interface Bar ()
- (void)barMethod;
@end
@implementation Bar
- (void)barMethod {
// do something
}
@end
除了在 Foo
实现之上移动 Bar
class 扩展之外,是否有任何方法可以在 FooBar.m 中转发声明 -[Bar barMethod]
(这不是很方便有时)?
出于方法可见性的目的,扩展的接口与任何其他接口一样:编译器必须在使用 之前查看声明。*不幸的是,您必须将 @interface
进入 header 或在文件中比 Foo
的实现更靠前。
*我所知道的一个例外是根本没有在接口中命名的方法——基本上由它们的定义声明——并且在同一个 @implementation
块中使用。无论顺序如何,编译器都会为您计算出来。