开发者

Only call function if another function is ready

How can i make sure in Objective-C, that a function only get called, until another function is ready?

Update:

-(void)reloadJsonFromServer {
    [[Sync sharedObject] synchronise];
    [self reload];
}

I've got this function. The second function "reload" should only be called, if the first function is开发者_开发技巧 – in this case it's a singlton – is ready. Ready means, that the first function is no more longer running.


So you want to wait on the completion of an asynchronous method? There's a whole bunch of ways to do that.

  • Make the synchronise method itself call reload on your object when it finishes
  • dispatch_async the reload method and have it just wait until the other method populates some flag or data structure that you are waiting on before continuing (BOOL synchronised or similar). Note that if your reload method does anything with UIKit, though, then you need to run it on the main thread.
  • Change the way synchronise runs so it doesn't actually return to the caller until it's done synchronising, but then dispatch_async the reloadJsonFromServer method.
  • Change synchronise as in the third point, but instead of using dispatch_async, add both of the method calls to an NSOperationQueue as NSOperations, with reload dependent on the completion of synchronise. The operation queue will handle it after that.

Those are just a few, I'm sure other people can suggest more.


In the last few days, i've learnd something about notifications. I think that is a good way too, to handle something like this. For more information about this look at this blog entry.

Custom Events in Objective-C


A bit late, but with NSNotification it can be handled.

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

[center addObserverForName:nil
                    object:nil
                     queue:nil
                usingBlock:^(NSNotification *notification)
{
     NSLog(@"%@", notification.name);
}];

Look at this: http://nshipster.com/nsnotification-and-nsnotificationcenter/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜