objective-c - 等待block完成再执行下一句代码
PHP中文网
PHP中文网 2017-04-22 09:00:22
0
1
570

我使用afnetworking发送一个post请求, 需要得到请求结果再执行下一步代码,现在我用过如下两种方式, 但都会造成程序卡住无法往下进行.但是我在另一个put请求用了相同的方法却可行, 哪位大神有了解过这种问题的?求解释

第一种: dispatch_semaphore_t

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
__block dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[manager POST:@"http://172.16.100.85:8080/service/user/register" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    self.requestResult = ProtocolErrorSuccess;
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        self.responseData = responseObject;
    }
    dispatch_semaphore_signal(sem);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    self.requestResult = ProtocolErrorFailure;

    dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

if(self.requestResult == ProtocolErrorSuccess) {
    [self saveToken:self.responseData];
}

第二种: NSCondition

__block NSCondition *condition = [[NSCondition alloc] init];

[manager POST:@"http://172.16.100.85:8080/service/user/register" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    self.requestResult = ProtocolErrorSuccess;
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        self.responseData = responseObject;
    }

    [condition lock];
    [condition signal];
    [condition unlock];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    self.requestResult = ProtocolErrorFailure;

    [condition lock];
    [condition signal];
    [condition unlock];
}];

[condition lock];
[condition wait];
[condition unlock];


if(self.requestResult == ProtocolErrorSuccess) {
    [self saveToken:self.responseData];
}
PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
大家讲道理

你方法锁住主线程能不卡住吗?success或者failure的block不是让你做下一步的事情的吗?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!