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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With