简体   繁体   English

我可以使用类方法作为委托回调吗

[英]Can I use a class method as a delegate callback

In a class method method I declare the following:在类方法方法中,我声明以下内容:

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Hello" 
                                                   message:@"World"
                                                  delegate:self
                                         cancelButtonTitle:@"Cancel" 
                                         otherButtonTitles:@"Done", nil];

Now even though the containing method is a class method, the compiler does not complain about the delegate:self .现在,即使包含方法是类方法,编译器也不会抱怨delegate:self Now to be the delegate I have to implement the method in UIAlertViewDelegate protocol.现在要成为委托,我必须在UIAlertViewDelegate协议中实现该方法。

Does it now matter, if the method is a class method or not, in order to be called when the user interacts with my AlertView?为了在用户与我的 AlertView 交互时调用该方法是否是类方法,现在是否重要?

I am asking this question, because my class does not have any instance variables so I would prefer it to contain class methods only.我问这个问题,因为我的类没有任何实例变量,所以我希望它只包含类方法。

I would like to share some of my findings:我想分享一些我的发现:

  1. It does not matter whether I declare the delegate like this delegate:self or delegate:[MyClass class]我是否像这样声明委托无关紧要delegate:selfdelegate:[MyClass class]

  2. However, it does matter how I declare the method:但是,我如何声明方法很重要:

    This works这有效

    +(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ // Some Actions here }

    Although the following "syntax" is the declaration in the UIAlertViewDelegate protocol, it does not work :尽管以下“语法”是UIAlertViewDelegate协议中的声明,但它不起作用

     // Mind the `-` sign at the start of the line. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ // Some Actions here }

First, I assume by "static" methods, you mean class methods (declared with + instead of - ).首先,我假设“静态”方法是指类方法(用+而不是-声明)。

"The compiler does not complain" about Objective-C doesn't always tell you much.关于 Objective-C 的“编译器不会抱怨”并不总是告诉你太多。 All it really means is that you have convinced the compiler that everything should (or at least could ) work at runtime.它真正的意思是你已经让编译器相信一切都应该(或至少可以)在运行时工作。

In the end, if the object you provide as a delegate responds to the right messages, the compiler won't care that it's a class (and neither will the runtime).最后,如果您作为委托提供的对象响应了正确的消息,则编译器不会在意它是一个类(运行时也不会)。 In this case, you are providing self from a class method.在这种情况下,您从类方法提供self It is as though you typed [MyClass class] .就好像您输入了[MyClass class]

I think it's probably questionable whether this is what you should do--but that's probably outside the bounds of your question.我认为这是否是您应该做的事情可能值得怀疑 - 但这可能超出了您的问题范围。

Yes you can !!!是的你可以 !!! A class is also an object.一个类也是一个对象。

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

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