views:

93

answers:

1

In the below code not invoked the willPresentAlertView method. Why? The method is static? or The Alert value is static?

@interface ShowAlert : NSObject <UIAlertViewDelegate>

static UIAlertView* alert;

    +(void) showAlert:(NSString*) msg{      
        alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@", msg] delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [alert show];
    }

    - (void)willPresentAlertView:(UIAlertView *)alertView {
        NSLOG(@"willPresentAlertView");
    }
+1  A: 

There's no such thing as a static method in Objective-C, and the storage classes of your variables have nothing to do with what UIKit does.

Here's what you did:

  1. You implemented a class method and created the alert in it.
  2. In this method, you set the alert's delegate as self; since this is in a class method, self is the class, which means you set the alert's delegate to the ShowAlert class.
  3. You showed the alert. Since the alert's delegate—the ShowAlert class—does not respond to willPresentAlertView:, the alert does not attempt to send that message.

“What!”, you say. “I implemented willPresentAlertView:!”

Well, yes, you implemented it as an instance method. Thus, instances of ShowAlert respond to that message. But the alert's delegate is not an instance of ShowAlert; it is the ShowAlert class itself, which does not respond to that message, because you implemented it as an instance method and not a class method.

I don't understand why you've made a class for this in the first place. Shouldn't whatever wants to show the alert create, be the delegate of, and show the alert itself? Why put another class in between? (Note that classes should generally be named for nouns, not verbs; the name of this class being “ShowAlert” is what tips me off that you're doing something wrong here.)

If you insist on having this class, you should either make each instance create, be the delegate of, and show a UIAlertView (and, accordingly, make alert an instance variable rather than a static variable in the implementation file), or make the class respond to willPresentAlertView: by changing your implementation of it from an instance method to a class method.

Peter Hosey