Andrii Chernenko
Andrii Chernenko

Reputation: 10204

How do I reference type in protocol declared in the same header?

I have the following construct:

//  WIWeatherService.h

@protocol WeatherRequestDelegate
- (void)didStartRequest:(WIWeatherRequest*)request;
- (void)didCancelRequest:(WIWeatherRequest*)request;
- (void)didReceiveResult:(WIWeatherResult*)result ForRequest:(WIWeatherRequest*)request;
- (void)request:(WIWeatherRequest*)request DidFailWithError:(NSError*) error;
@end

@interface WIWeatherRequest : NSObject

@property (strong, nonatomic) id<WeatherRequestDelegate> delegate;

@end

The problem is that interface is unknown to the protocol (since it is declared later) and vice versa if I declare protocol after interface. If I move protocol declaration to a separate file , compiler would probably complain about circular dependency.

Is there any way to resolve this situation?

Upvotes: 0

Views: 20

Answers (1)

Sulthan
Sulthan

Reputation: 130152

The solution is pretty standard, it's called forward declaration

Add

@class WIWeatherRequest;

to the very beginning.

A forward declaration has the following meaning:
Compiler, please, know that identifier WIWeatherRequest is a class. I will define it later.

This is the inheritance of the C-language from the old times when compilers were able to read only 1 file at a time, and only sequentially from top to bottom (the actual reason C introduced headers. Every header is one big forward declaration).

Upvotes: 2

Related Questions