My idea is very similar to declare a variable of an interface type in java.
我的想法非常类似于在java中声明一个接口类型的变量。
So for example,
例如,
header file 1:
头文件1:
@protocol Calculator
@end
I then define an @interface CalculatorImpl
which implements the above Calculator
protocol.
然后我定义了一个@interface CalculatorImpl,它实现了上面的Calculator协议。
In header file 2:
在头文件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
但是,xcode会在计算器行标记错误
property with 'weak' attribute must be of object type
Is this usage of protocol disallowed by objective-c?
Objective-c是否禁止使用协议?
2 个解决方案
#1
20
A @protocol
isn't a type so you can't use it for the type of a @property
.
@protocol不是一个类型,所以你不能将它用作@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.
这声明了一个属性,对其类型没有限制,只不过它符合Calculator协议。
#2
4
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.
在Objective-C中,您无法实例化协议,您只能遵守它。因此,您应该拥有一个符合Calculator协议的通用对象,而不是具有Calculator类型的对象。
Otherwise you can use
否则你可以使用
@property (weak, nonatomic) CalculatorImpl* calculator;
since CalculatorImpl
is an interface, not a protocol.
因为CalculatorImpl是一个接口,而不是一个协议。
#1
20
A @protocol
isn't a type so you can't use it for the type of a @property
.
@protocol不是一个类型,所以你不能将它用作@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.
这声明了一个属性,对其类型没有限制,只不过它符合Calculator协议。
#2
4
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.
在Objective-C中,您无法实例化协议,您只能遵守它。因此,您应该拥有一个符合Calculator协议的通用对象,而不是具有Calculator类型的对象。
Otherwise you can use
否则你可以使用
@property (weak, nonatomic) CalculatorImpl* calculator;
since CalculatorImpl
is an interface, not a protocol.
因为CalculatorImpl是一个接口,而不是一个协议。