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

Bes*_*esi 12 cocoa-touch objective-c ios

在类方法方法中,我声明如下:

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Hello" 
                                                   message:@"World"
                                                  delegate:self
                                         cancelButtonTitle:@"Cancel" 
                                         otherButtonTitles:@"Done", nil];
Run Code Online (Sandbox Code Playgroud)

现在即使包含方法是类方法,编译器也不会抱怨delegate:self.现在成为委托我必须在UIAlertViewDelegate协议中实现该方法.

现在重要的是,如果方法是类方法,还是在用户与我的AlertView交互时调用?

我问这个问题,因为我的类没有任何实例变量,所以我更喜欢它只包含类方法.

Bes*_*esi 14

我想分享一些我的发现:

  1. 无论我是否声明代表这样delegate:self或者无关紧要delegate:[MyClass class]

  2. 但是,我如何声明方法并不重要:

    这有效

    +(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        // Some Actions here
    }
    
    Run Code Online (Sandbox Code Playgroud)

    虽然以下"语法"是UIAlertViewDelegate协议中的声明,但它不起作用:

    -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        // Some Actions here
    }
    
    Run Code Online (Sandbox Code Playgroud)


hus*_*had 11

首先,我假设"静态"方法,你的意思是类方法(用+而不是声明-).

关于Objective-C的"编译器没有抱怨"并不总能告诉你.它真正意味着你已经说服编译器所有东西都应该(或者至少可以)在运行时工作.

最后,如果您作为委托提供的对象响应正确的消息,编译器将不关心它是否为类(运行时也不会).在这种情况下,您self将从类方法提供.就好像你打字一样[MyClass class].

我认为这是否是你应该做的事可能有问题- 但这可能超出了你的问题范围.