Understanding handler parameter in UIAlertAction Method

Hello,


I am working on an application in which I want to display an alert message when the user presses a button. So far, I have following code for the alert message itself:


NSString *userText = [NSString stringWithFormat:@"Hello %@", self.nameBox.text];

UIAlertController *alertMessage = [UIAlertController alertControllerWithTitle:@"Welcome to iOS"
                                                                         message:userText
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];


I understand what is going on here, where I am confused is the alertWithTitle:style:handler method, specicially the handler parameter. I have code posted online where they wrote in

^(UIAlertAction * action)


UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
                                                          style:UIAlertActionStyleCancel
                                                        handler:nil];



I passed in nil, Is this a bad practice, also, could someone explain what this line means and why it should be used instead: ^(UIAlertAction * action)

You will be adding that "cancelAction" as a 'button' entitled "Cancel" under that alert. When the user taps "Cancel" the program will stop displaying the alert and the "Cancel" button and will perform whatever code you give it in that "handler". If you give it "nil" then it will do nothing. If you give it something like:

handler:^(UIAlertAction * action) {
     [[NSUserDefaults standardUserDefaults] setObject:[NSDate date]  forKey:@"Date latest response"];
     aDateVariableInCode=[NSDate date];
        }

// the next line ends this line defining cancelAction:
  ];

then the code will (just as an example) store the current date in NSUserDefaults and will set a variable in your code equal to that date. You can do whatever you want in that handler that is appropriate for the user having tapped "Cancel". You can use the object "action" in that handler if you wish.


If you are familiar with the older UIAlertView, this is the code that used to go in the delagate method:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

So if I just want the Cancel button to dismiss the view, I can leave it as nil? Also, do you know what this statement means: ^(UIAlertAction * action)

Yes - you can leave it nil.

If I reword your question to


What does this mean:

handler:^(UIAlertAction * action){....}

Then the answer is - you place the code for the handler where the "..." is. That code will be called when the user taps the button associated with that UIAlertAction. In that code you can refer to the object "action" and get the properties of the UIAlertAction (i.e. thge button) that called the code.

Understanding handler parameter in UIAlertAction Method
 
 
Q