开发者

Simulate asynchronous function call

I have an asset manager that needs to notify the owner it's assets are ready. I'm sending a token back for the consumer to listen to listen for a notification to avoid tighter coupling. The issue is when the assets are already loaded I need to call the loadComplete after a delay. What's the best way to do this in objective-c?

Asset Manager

-(tokenString*) loadAssetPath:(NSString*) asset {
    //start asynchronous load
    //or if assets ready send complete       <-- issue
    return nonceToken;
}
-(void)loadComplete {
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:tokenString object:self];
}

Consumer

NSString* token;
-(void) loadSomething {
    if(token)
        [self removeListener];开发者_如何学JAVA
    token = [[AssetManager sharedManager] 
        loadAssetPath:@"http://server.dev/myLargeImage.png"];
    [[NSNotificationCenter defaultCenter] 
        addObserver:[AssetManager sharedManager] 
        selector:@selector(assetLoaded:) name:token];
}
-(void)assetLoader:(NSNotifcation*)aNotification {
    [self removeListener];
    //continue on with stuffing stuff
}


Use NSObject's performSelector function which allows it to be called after a delay.

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

You can even use a form of this function to run it on another thread, which is useful to not blocking the main thread when doing lengthy operations (just don't muck with the UI objects in this thread).


@DavidNeiss is correct about performSelector:withObject:afterDelay:, but you almost certainly don't want an actual time delay here. At most you want to perform your selector on the next event loop, just so things are consistent for the listener. So you should make the delay 0. This differs from the normal performSelect:withObject: which will immediately perform the selector synchronously.

-(tokenString*) loadAssetPath:(NSString*) asset {
    //start asynchronous load
    if (<load is actually complete>) {
        // -loadComplete will execute on the next event loop
        [self performSelector:@selector(loadComplete) withObject:nil afterDelay:0];
    }

    return nonceToken;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜