我创建了这样的块:
1)定义自己的完成块,
typedef void(^myCompletion)(BOOL);
2)创建一个将完成块作为参数的方法
-(void) myMethod:(myCompletion) compblock{
//do stuff
compblock(YES);
}
3)这就是你如何使用它,
[self myMethod:^(BOOL finished) {
if(finished){
NSLog(@"success");
}
}];
如何在块中发送数组然后从块中获取新数组?
//here I get array of image id's and go in loop for download it all,
NSString *URLString = [NSString stringWithFormat: @"%@", requestString];
NSURL * url = [NSURL URLWithString:URLString];
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
userWithImage = [responseObject copy];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image error: %@", error);
}];
[requestOperation start];
//here I save it to mutable array and send as completion block,
是的,我认为发送1个图像ID并在块1图像中返回会更好。在方法中,我将调用块 - 单独使用照片进行操作。那么,有可能吗? 我可以使用NSNotifications做这样的事情,但是当它可以在块中时会更广泛。
答案 0 :(得分:4)
1)定义自己的完成块
typedef void(^myCompletion)(BOOL finished, NSArray *myArray);
2)创建一个将完成块作为参数的方法
-(void)myMethod:(myCompletion)compblock {
//do stuff
NSArray *myArray = ...;
compblock(YES, myArray);
}
3)这就是你如何使用它,
[self myMethod:^(BOOL finished, NSArray *myArray) {
if (finished){
NSLog(@"success");
}
}];
答案 1 :(得分:0)
如果您只想围绕AFNetworking
请求编写包装器,可以编写如下方法:
- (void)downloadImageWithPath:(NSString *)path completion:(void (^)(AFHTTPRequestOperation *operation, UIImage *image, NSError *error))completion __attribute__((nonnull(2)));
{
NSParameterAssert(completion);
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
completion(operation, responseObject, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(operation, nil, error);
}];
[requestOperation start];
}
您可以使用以下内容调用此方法:
[self downloadImageWithPath:@"http://url/to/image.jpg"
completion:^(AFHTTPRequestOperation *operation, UIImage *image, NSError *error) {
if (error) {
// handle error
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI with image
});
}];