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 callreload
on your object when it finishes dispatch_async
thereload
method and have it justwait
until the other method populates some flag or data structure that you are waiting on before continuing (BOOL synchronised
or similar). Note that if yourreload
method does anything withUIKit
, 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 thendispatch_async
thereloadJsonFromServer
method. - Change
synchronise
as in the third point, but instead of usingdispatch_async
, add both of the method calls to anNSOperationQueue
asNSOperation
s, withreload
dependent on the completion ofsynchronise
. 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/
精彩评论