Pregunta

I have a UIAlertView that I display with no buttons. I'd like to programmatically dismiss it after some action is processed (it is a "Please wait" alert dialog). I'd like to dismiss it, though, without the need for the UIAlertView to be a property.

Why: Now I am allocating the alert view to a @property - e.g.: I am creating a class variable. I don't feel like it deserves to have it that way - because frankly, it is displayed only when the View Controller is loading. I thought it is somehow added as a subview, that I could pop it from the stack when the loading is done, but that didn't work.

What: I create the alert dialog (no buttons) and show it. Then I start processing data - syncing with server. It only happens once and it is not a frequent thing. However, other object takes care of the sync and is implemented as observer pattern - the object itself reports, when the data has been loaded. That's when I dismiss the dialog. I just wanted to avoid using @property for the dialog.

This is how I do it (simplified):

@property (nonatomic, strong) UIAlertView *av;

- (void)setup {
       ...
       [self.av show];
       [self loadData];
}

- (void)loadData {
       ...loading data...
       [self.av dismissWithClickedButtonIndex:0 animated:YES];
}

Is there a way how to dismiss it without the need for "storing" it to @property?

¿Fue útil?

Solución

Blocks retain variables they capture. You can take advantage of that behaviour, but you should understand what you're doing there:

UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Title"
                                             message:@"Message"
                                            delegate:nil
                                   cancelButtonTitle:nil
                                   otherButtonTitles:nil];
[av show];

dispatch_async(dispatch_queue_create("com.mycompany.myqueue", 0), ^{
    sleep(5);
    dispatch_async(dispatch_get_main_queue(), ^{
        [av dismissWithClickedButtonIndex:0 animated:YES];
    });
});

The sleep(5) is just simulating your long running task.

Instead of using UIAlertView, I'd consider using a library like this: https://github.com/jdg/MBProgressHUD

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top