简体   繁体   English

如何调用委托的函数而不在ios中找到“实例方法未找到”警告?

[英]How to call a delegate's function without getting the “instance method not found” warning in ios?

In the apps I worked on, I often found such lines of code 在我工作的应用程序中,我经常发现这样的代码行

[delegate aFunction]; [委托aFunction];

that generated the "instance method "aFunction" not found (return type defaults to id)" warning 生成“实例方法”aFunction“未找到(返回类型默认为id)”警告

Now, I did a bit of research on SO and found out that the warning can be removed by declaring the function for cases when you call it on self ([self aFunction];), but none of the answers said anything about my case, when I use a delegate. 现在,我对SO进行了一些研究,发现当你在self([self aFunction];)上调用它时,通过声明函数可以删除警告,但没有一个答案说明了我的情况,当我使用代表。

So, long story short, what can I do to correctly call a delegate's method inside another class? 所以,长话短说,我该怎么做才能在另一个类中正确调用委托的方法? Things appear to work fine, so this is not a major issue, but a warning means I'm not doing something completely correct so I would like to learn what's the best practice for such cases 事情似乎工作正常,所以这不是一个主要问题,但警告意味着我没有做一些完全正确的事情所以我想知道这种情况的最佳做法是什么

Thank you for your help in advance! 提前谢谢你的帮助!

So, if I'm understanding you correctly, your issues can be taken away by declaring your protocol as follows: 所以,如果我正确理解你,可以通过声明你的协议如下来解决你的问题:

@class SomeClass;
@protocol SomeClassDelegate <NSObject>
@required
- (void)thisObjectDidSomething:(SomeClass*)instance;
@optional
- (void)thisObjectDidSomethingUnimportant:(SomeClass*)instance;
@end

Then your delegate ivar and property look like this (use assign instead of weak if you're not using ARC): 然后你的代表ivar和属性看起来像这样(如果你没有使用ARC,请使用assign而不是weak):

@interface SomeClass () {
    __weak id<SomeClassDelegate> delegate_;
}
@property (weak) id<SomeClassDelegate> delegate;

And in the .h file of any class that's going to implement that protocol, do this: 在要实现该协议的任何类的.h文件中,执行以下操作:

@interface TCReader : NSObject <SomeClassDelegate> {

}

Since it's safe to call selectors on nil, for required methods, you can just: 由于在nil上调用选择器是安全的,对于所需的方法,您可以:

[self.delegate thisObjectDidSomething:self]

But for optional methods, you'd better: 但对于可选方法,你最好:

if ([self.delegate respondsToSelector:@selector(thisObjectDidSomethingUnimportant:)]) {
    [self.delegate thisObjectDidSomethingUnimportant:self]
}

The main point here is that by declaring and making use of a protocol, you let XCode know that those methods are defined for objects implementing the protocol. 这里的要点是通过声明和使用协议,让XCode知道为实现协议的对象定义了那些方法。 If you require that your delegate implement that protocol, then Xcode knows that your delegate has those methods defined. 如果您要求您的委托实现该协议,则Xcode知道您的委托已定义了这些方法。

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

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