1

以下代码产生错误No visible @interface for 'Bar'在以下实现的第二行声明选择器 'barMethod' -[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

除了将类扩展移到实现之上(有时不是很方便)之外,还有什么方法可以-[Bar barMethod]在 FooBar.m中转发声明?BarFoo

4

1 回答 1

1

出于方法可见性的目的,扩展的接口与其他任何接口一样:编译器必须在使用之前查看声明。*不幸的是,您必须将@interface要么放入标题中,要么放在文件中比Foo' 的实现更靠前的位置。


*我知道的一个例外是根本没有在接口中命名的方法——基本上是由它们的定义声明的——并且在同一个@implementation块中使用。无论顺序如何,编译器都会为您解决这个问题。

于 2015-03-20T01:45:49.043 回答