开发者

Dismiss alert view after waiting for another object to finish working

开发者 https://www.devze.com 2023-03-30 07:25 出处:网络
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

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 tha开发者_运维知识库t 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 ServerConnection class 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 ServerConnection object receives a server response, you can have it run the completion block.


Use NSNotification. Have the object handling the server request post a notification that it is complete. Have your home view controller listen for it and respond accordingly.

0

精彩评论

暂无评论...
验证码 换一张
取 消