I have a view controller, let’s call it HomeViewController, that pops up an alert view without any buttons that says “Please wait while connecting to the server”. While waiting, the view controller calls a method in another class (ServerConnection) which sends data to the server.
What I need to do is cancel that alert once I receive a server response, but it won’t work if I do the following:
HomeViewController *hvc = [[HomeViewController alloc] init];
[hvc waitAlertCancel];
//note:waitAlertCancel is a method that calls the following line of code:
[waitAlert dismissWithClickedButtonIndex:0 animated:TRUE];
What should I do to be able to cancel that alert view from another class?
Blocks are awesome.
If you need to call code in one class from another class after an event occurs, blocks are the perfect solution. Before blocks were available, you’d typically handle a design like this using a delegate pattern, which is fine, but it can be heavy-handed in situations like yours where you just need to dismiss an alert. So, using blocks is a much cleaner solution, IMO.
Create a method in your
ServerConnectionclass that uses blocks for a callback. Something along the lines of- (void) connectWithCompletionBlock(void(^))completionBlock;Then you would call the
connectWithCompletionBlock:method like this:[myServerConnection connectWithCompletionBlock: ^ { [waitAlert dismissWithClickedButtonIndex:0 animated:TRUE]; }];Once the
ServerConnectionobject receives a server response, you can have it run the completion block.