释放阻止或取消阻止对象

时间:2014-03-23 08:40:30

标签: objective-c objective-c-blocks

使用Class进行所有网络调用以获取数据。

// Helper Class method for network calls
- (void) dataForUser:user withCompletionHandler:(void(^)(id response)) onComplete {
    [[webClient sharedObject] fetchDataForUser:user withCompletionHandler:(void(^)(id response)) onComplete {
        // do something to get data
        onComplete(data);
    }];
}

// View Controller's Model Class

- (void) getDataWithCompletionHandler:(void(^)(id)) onComplete {
    // helperClassObj is a class variable
    [helperClassObj dataForUser:userInfo withCompletionHandler:^(id response) {
        // process response and store it as response 1.
        onComplete(response1);
    }];
}

在完成之前我无法再提出其他请求。如何取消之前的请求,以便我不必等到获取数据。就像我为user1请求数据并请求user2的数据一样,我需要显示user2数据并能够取消之前的通话。

1 个答案:

答案 0 :(得分:1)

// Helper Class method for network calls
- (void) dataForUser:user withCompletionHandler:(void(^)(id response)) onComplete {
    [webClient fetchDataForUser:user withCompletionHandler:^(id response) {
        // do something to get data
        if(onComplete) {
            onComplete(data);
        }

    }];
}

// View Controller's Model Class

BOOL isLastRequestCancelled = NO;

- (void) getDataWithCompletionHandler:(void(^)(id)) onComplete {
    isLastRequestCancelled = YES;
    // helperClassObj is a class variable
    [helperClassObj dataForUser:userInfo withCompletionHandler:^(id response) {
        // process response and store it as response1
        if(!isLastRequestCancelled) {
            if(onComplete) {
                onComplete(response1);
            }
        }

        isLastRequestCancelled = NO;
    }];
}