Iphone 目标-C GCD等待区块完成(AFD网络)
我一直在尝试使用教程中的一些代码,但是由于没有了解GCD,所以没有取得太大的成功 我有一个名为API.m的类,下面是关于GCD的代码:Iphone 目标-C GCD等待区块完成(AFD网络),iphone,objective-c,xcode,grand-central-dispatch,afnetworking,Iphone,Objective C,Xcode,Grand Central Dispatch,Afnetworking,我一直在尝试使用教程中的一些代码,但是由于没有了解GCD,所以没有取得太大的成功 我有一个名为API.m的类,下面是关于GCD的代码: + (API *) sharedInstance { static API *sharedInstance = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ sharedInstance = [[self al
+ (API *) sharedInstance
{
static API *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:APIHost]];
});
return sharedInstance;
}
-(void)commandWithParams:(NSMutableDictionary*)params
onCompletion:(JSONResponseBlock)completionBlock
{
NSMutableURLRequest *apiRequest = [self multipartFormRequestWithMethod:@"POST"
path:APIPath
parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//TODO: attach file if needed
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
}];
[operation start];
}
现在,当我第一次单击按钮时,一个空的NSArray被打印到输出窗口,但当我再次按下它时,打印的是“1”。很明显,程序在完成块有时间完全执行之前到达NSLog。有人能帮我修改代码,这样我就可以选择在完成块完成后执行NSLog吗?不确定您要完成什么,但如果目标是在完成块完成后执行NSLog,您可以在完成块后移动NSLog语句
[self.users addObject:@"1"];
如果在将代码添加到数组后,有一些代码要执行,则可以
[self methodName]; in the completion block and it will get called there.
完成块,是在执行您想要运行的代码之后运行的代码。您希望运行的代码将在另一个线程上异步运行。运行该代码后,将执行完成块代码。不确定要完成什么,但如果目标是在完成块之后执行NSLog,则可以在完成块之后移动NSLog语句
[self.users addObject:@"1"];
如果在将代码添加到数组后,有一些代码要执行,则可以
[self methodName]; in the completion block and it will get called there.
完成块,是在执行您想要运行的代码之后运行的代码。您希望运行的代码将在另一个线程上异步运行。运行该代码后,将执行完成块代码。关于块的这种用法的全部内容是立即返回。如果你不想要它,就用不同的方法。使用块的全部原因是它会立即返回。如果你不想要它,用不同的东西。