需要帮助理解objective-c协议

时间:2022-09-07 08:51:45
#import <UIKit/UIKit.h>

@protocol myProtocol <NSObject>

-(void)aMethod;

@end

@interface ViewController : UIViewController

@property (weak) id<myProtocol> dSource;

@end

I am trying to get a firm grip on Obj-c protocols, I am reading apple doc to study, few things are not clear to me. Below are the points from doc:

我试图牢牢掌握Obj-c协议,我正在阅读苹果医生研究,很少有事情我不清楚。以下是doc的要点:

  1. The pie chart view class interface would need a property to keep track of the data source object. (The code above, we mostly declare protocol this way, when I have protocol declared in my class why need a tracking object, Or protocol can be defined in independent class? and for that we need tracking object?)

    饼图视图类接口需要一个属性来跟踪数据源对象。 (上面的代码,我们大多以这种方式声明协议,当我在我的类中声明协议为什么需要一个跟踪对象,或者协议可以在独立的类中定义?为此我们需要跟踪对象?)

  2. By specifying the required protocol conformance on the property, you’ll get a compiler warning if you attempt to set the property to an object that doesn’t conform to the protocol.

    通过在属性上指定所需的协议一致性,如果尝试将属性设置为不符合协议的对象,则会收到编译器警告。

  3. If you attempt to call the respondsToSelector: method on an id conforming to the protocol as it’s defined above, you’ll get a compiler error that there’s no known instance method for it. Once you qualify an id with a protocol, all static type-checking comes back; you’ll get an error if you try to call any method that isn’t defined in the specified protocol. One way to avoid the compiler error is to set the custom protocol to adopt the NSObject protocol.

    如果您尝试在符合上面定义的协议的id上调用respondsToSelector:方法,您将得到一个编译器错误,即没有已知的实例方法。一旦使用协议限定id,所有静态类型检查都会返回;如果您尝试调用未在指定协议中定义的任何方法,则会收到错误。避免编译器错误的一种方法是将自定义协议设置为采用NSObject协议。

1 个解决方案

#1


1  

  1. I dont understand this question
  2. 我不明白这个问题
  3. Correct, the property requires that the property is an id which conforms to your property, if you try to set it to something else the compiler rightly complains
  4. 正确,该属性要求属性是一个符合您的属性的id,如果你试图将它设置为其他编译器正确抱怨的东西
  5. This is because respondsToSelector: is a method on the NSObject protocol, so you can either have your protocol extend NSObject (standard), or you could declare the property as NSObject
  6. 这是因为respondsToSelector:是NSObject协议上的一个方法,所以你可以让你的协议扩展NSObject(标准),或者你可以将属性声明为NSObject

#1


1  

  1. I dont understand this question
  2. 我不明白这个问题
  3. Correct, the property requires that the property is an id which conforms to your property, if you try to set it to something else the compiler rightly complains
  4. 正确,该属性要求属性是一个符合您的属性的id,如果你试图将它设置为其他编译器正确抱怨的东西
  5. This is because respondsToSelector: is a method on the NSObject protocol, so you can either have your protocol extend NSObject (standard), or you could declare the property as NSObject
  6. 这是因为respondsToSelector:是NSObject协议上的一个方法,所以你可以让你的协议扩展NSObject(标准),或者你可以将属性声明为NSObject