I’m having a lot of trouble trying to get my Objective-C code to wait appropriately for user input from a UIAlertView before triggering subsequent code. For example, I have the following code:
if (!self.currentUser) [self displayLoginUIAlertView];
Program *program = [[Program alloc] initWithUser:self.currentUser];
[program startProgram];
Where Program is a custom object and where user input from [self displayLoginUIAlertView] sets the property self.currentUser.
I would prefer not to put the second and third lines (Program *program and [program startProgram] into alertView:didDismissWithButtonIndex as I am trying to limit the number of different types of alert views in my view controller. Additionally, I would prefer not to create my own custom fully-modal UIAlertView object (as some solutions online have seemed to suggest).
The answer I am looking for will hopefully be generalizable beyond UIAlertView objects and will help answer the more general question of how to wait for a line in Objective-C to execute fully before moving onto the next lines of code. I have also tried the following:
if (!self.currentUser) [self displayLoginUIAlertView];
while (!self.currentUser) wait(1);
Program *program = [[Program alloc] initWithUser:self.currentUser];
[program startProgram];
However, this (unsurprisingly) leads to an infinite loop wherein the alert view never appears and user input is locked out.
I have looked into using blocks but am super-confused by their syntax. Are blocks the solution? Or am I asking the wrong question?
The proper way is indeed to implement
alertView:didDismissWithButtonIndex:at al.However, you might want to create an object that can take a callback block and act as a delegate for your
UIAlertView, but I think it’s more trouble than it’s worth.. (you’d have to keep your delegate object in an instance variable reference to keep it from being dismissed)