Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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?

like image 396
Anthony Kong Avatar asked Feb 20 '12 12:02

Anthony Kong


2 Answers

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.

like image 39
Manlio Avatar answered Sep 23 '22 08:09

Manlio


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.

like image 160
yuji Avatar answered Sep 25 '22 08:09

yuji