我可以在 Objective-C 接口中声明一个“协议"类型的变量吗? [英] Can I declare a variable of a 'protocol' type in an Objective-C interface?

查看:47
本文介绍了我可以在 Objective-C 接口中声明一个“协议"类型的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的想法很像在java中声明一个接口类型的变量.

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

例如,

头文件 1:

@protocol Calculator

@end

然后我定义了一个 @interface CalculatorImpl 来实现上面的 Calculator 协议.

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

在头文件 2 中:

@interface SomeViewController : UIViewController {


}

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

@end

但是,xcode 会在计算器行标记错误

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

property with 'weak' attribute must be of object type 

objective-c 是否不允许使用这种协议?

Is this usage of protocol disallowed by objective-c?

推荐答案

@protocol 不是一个类型,所以你不能将它用于 @property<的类型/代码>.

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

你可能想做的是:

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

这声明了一个对其类型没有限制的属性,只是它符合Calculator协议.

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

这篇关于我可以在 Objective-C 接口中声明一个“协议"类型的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆