Alexander Vasenin
Alexander Vasenin

Reputation: 12953

Forward declaration of objective-c class extension method

The following code produces error 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

Is there any way to forward declare -[Bar barMethod] inside FooBar.m other than moving Bar class extension above Foo implementation (which is not very convenient at times)?

Upvotes: 1

Views: 538

Answers (1)

jscs
jscs

Reputation: 64002

An extension's interface is like any other for purposes of method visibility: the compiler has to see the declaration before the use.* Unfortunately, you will have to put the @interface either into a header or further up in the file than Foo's implementation.


*The one exception to this that I know of is for methods that are not named in an interface at all -- essentially declared by their definition -- and used within the same @implementation block. The compiler will figure that out for you regardless of the order.

Upvotes: 1

Related Questions