Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Now to be the delegate I have to implement the method in UIAlertViewDelegate protocol.

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?

I am asking this question, because my class does not have any instance variables so I would prefer it to contain class methods only.

like image 492
Besi Avatar asked Jan 16 '12 17:01

Besi


2 Answers

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]

  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:

    // Mind the `-` sign at the start of the line.
    -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        // Some Actions here
    }
    
like image 154
Besi Avatar answered Oct 05 '22 12:10

Besi


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. 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. It is as though you typed [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.

like image 23
huskerchad Avatar answered Oct 05 '22 12:10

huskerchad