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.
I would like to share some of my findings:
It does not matter whether I declare the delegate like this delegate:self
or delegate:[MyClass class]
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With