在后台做点什么,ONCE完成,在前台做点什么?

时间:2012-05-21 07:12:02

标签: objective-c xcode automatic-ref-counting default

我们面临着类似的情况。假设我们想从网上获取数据。所以,我们从后台获取数据。之后我们回来并根据新数据更新一些视图。

我应该这样做:

__block NSDictionary * dic = nil;
__block NSObject* lock = [[NSObject alloc]init];

[Tools doBackground:^{
    @synchronized (lock) {
        dic=(NSDictionary *)[GrabClass JsonParser:alamat];
    }
}];
@synchronized (lock)
{
}

NSString *countView= [[dic objectForKey:[BNUtilitiesQuick currentBusiness].ID] objectForKey:@"CountViews"];

... bla bla bla

或者我应该

[Tools doBackground:^{
        dic=(NSDictionary *)[GrabClass JsonParser:alamat];
    //}
    [Tools doForeGround:^{
        NSString *countView= [[dic objectForKey:businessReviewed.ID] objectForKey:@"CountViews"];

        CLog(@"countView:%@", countView);
        NSString *countReview=[[dic objectForKey:businessReviewed.ID] objectForKey:@"Review"];

当然:

NSString *countReview=[[dic objectForKey:businessReviewed.ID] objectForKey:@"Review"]; 必须在dic=(NSDictionary *)[GrabClass JsonParser:alamat];完成后调用,不用说。

这也是doForeGround和doBackGround

的定义
+(void)doForeGround:(void (^)())block
{
    dispatch_async(dispatch_get_main_queue(), ^{
        block();
    });
}

+(void)doBackground:(void (^)())block
{
    //DISPATCH_QUEUE_PRIORITY_HIGH
    //dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), ^{
    dispatch_async(dispatch_get_global_queue(-2,0), ^{
        block();
    });
}

1 个答案:

答案 0 :(得分:2)

以下是如何使用GCD的简单示例

dispatch_queue_t queue;
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);

    //Do stuff async in the backbround
    dispatch_async(queue, ^{

        dispatch_sync(queue, ^{
            //Fetch data sync. When its done... update.
        });

        //Update on the main thread
        dispatch_sync(dispatch_get_main_queue(), ^{
            //Do some updates
        });
    });