简体   繁体   English

在Objective-C中实现协议方法

[英]implementing protocol methods in objective-c

If I have an protocol (say UIPickerViewDataSource) and I implement its required methods, do I need to declare those methods in the header file of my class? 如果我有一个协议(例如UIPickerViewDataSource)并且实现了所需的方法,是否需要在类的头文件中声明这些方法?

At the moment I'm not doing so and I get a warning of incomplete implementation (although everything works fine). 目前,我还没有这样做,但是我收到了实施不完整的警告(尽管一切正常)。 If I do add the required methods in the then I don't get such warning: 如果我确实在中添加了必需的方法,那么我不会得到这样的警告:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;

Is this the correct behaviour? 这是正确的行为吗? Is it really necessary to add the declaration for required protocol methods in the header file of my class? 确实需要在类的头文件中添加必需协议方法的声明吗?

No, you don't. 不,你没有。 Declaring that the class implements that protocol and implementing the methods is enough. 声明该类实现了该协议并实现了方法就足够了。 You could still declare them in the header for documentation purposes, though. 但是,出于文档目的,您仍然可以在标头中声明它们。

The correct way is to declare that your class implements the protocol. 正确的方法是声明您的类已实现该协议。 If for instance your class is called LordSandwichViewController , then your class interface must look like this: 例如,如果您的类称为LordSandwichViewController ,则您的类接口必须如下所示:

@interface LordSandwichViewController : UIViewController <UIPickerViewDataSource> {
{
}

So you don't declare the protocol methods in your class interface, only the protocol. 因此,您不必在类接口中声明协议方法,而只能声明协议。

Incomplete implementation warnings tell you that you are not implementing all the required methods you are either: 不完整的实施警告会告诉您您没有实现以下所有必需的方法:

  1. Defining in your header. 定义标题。
  2. Declaring a method required by a protocol you're conforming to. 声明您要遵循的协议所需的方法。

Look at what methods it's expecting, and implement those. 查看期望的方法,然后实现这些方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM