Anthony Kong
Anthony Kong

Reputation: 40664

Can I declare a variable of a 'protocol' type in an Objective-C interface?

My idea is very similar to declare a variable of an interface type in java.

So for example,

header file 1:

@protocol Calculator

@end

I then define an @interface CalculatorImpl which implements the above Calculator protocol.

In header file 2:

@interface SomeViewController : UIViewController {


}

@property (weak, nonatomic) IBOutlet UITextField *txtResult;
@property (weak, nonatomic) Calculator* calculator;

@end

However, the xcode will flag an error at the calculator line

property with 'weak' attribute must be of object type 

Is this usage of protocol disallowed by objective-c?

Upvotes: 16

Views: 8053

Answers (2)

Manlio
Manlio

Reputation: 10865

You should use

@property (weak, nonatomic) id <Calculator> calculator;

In Objective-C you cannot instantiate a protocol, you can only be conform to it. Thus, instead of having an object of type Calculator, you should have a generic object that is conform to Calculator protocol.

Otherwise you can use

@property (weak, nonatomic) CalculatorImpl* calculator;

since CalculatorImpl is an interface, not a protocol.

Upvotes: 5

yuji
yuji

Reputation: 16725

A @protocol isn't a type so you can't use it for the type of a @property.

What you probably want to do instead is this:

@property (weak, nonatomic) id <Calculator> calculator;

This declares a property with no restriction on its type, except that it conforms to the Calculator protocol.

Upvotes: 34

Related Questions