Completion Handler 和 Blocks 的区别:[iOS]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39609727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference Between Completion Handler and Blocks : [iOS]
提问by shubham mishra
I am messed with both completion handler and blocks while I am using them in Swift
and Objective-C
. And when I am searching blocks in Swift
on google it is showing result for completion handler! Can somebody tell me what is the difference between completion handler and blocks with respect to Swift
and Objective-C
?
当我在Swift
and 中使用它们时,我对完成处理程序和块都感到困惑Objective-C
。当我Swift
在谷歌上搜索块时,它显示了完成处理程序的结果!有人能告诉我关于Swift
and 的完成处理程序和块之间有什么区别Objective-C
吗?
回答by vaibhav
Here you can easily differentiate between blocks and completion handlers in fact both are blocks see detail below.
在这里,您可以轻松区分块和完成处理程序,实际上它们都是块,请参阅下面的详细信息。
Blocks:
块:
Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary.
块是添加到 C、Objective-C 和 C++ 的语言级功能,它允许您创建不同的代码段,这些代码段可以像值一样传递给方法或函数。块是 Objective-C 对象,这意味着它们可以添加到像 NSArray 或 NSDictionary 这样的集合中。
- They can be executed in a later time, and not when the code of the scope they have been implemented is being executed.
- Their usage leads eventually to a much cleaner and tidier code writing, as they can be used instead of delegate methods, written just in one place and not spread to many files.
- 它们可以在以后执行,而不是在执行它们的范围内的代码时执行。
- 它们的使用最终会导致代码编写更加干净整洁,因为它们可以代替委托方法使用,只在一个地方编写,而不是扩展到许多文件。
Syntax:ReturnType (^blockName)(Parameters) see example:
语法:ReturnType (^blockName)(Parameters)参见示例:
int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger); // anInteger outside variables
};
// calling blocks like
testBlock();
Block with argument:
带参数的块:
double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
};
// calling with parameter
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);
Completion handler:
完成处理程序:
Whereas completion handler is a way (technique) for implementing callback functionality using blocks.
而完成处理程序是一种使用块实现回调功能的方式(技术)。
A completion handler is nothing more than a simple block declaration passed as a parameter to a method that needs to make a callback at a later time.
完成处理程序只不过是作为参数传递给稍后需要进行回调的方法的简单块声明。
Note: completion handler should always be the last parameter in a method. A method can have as many arguments as you want, but always have the completion handler as the last argument in the parameters list.
注意:完成处理程序应该始终是方法中的最后一个参数。一个方法可以有任意多的参数,但始终将完成处理程序作为参数列表中的最后一个参数。
Example:
例子:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;
// calling
[self beginTaskWithName:@"MyTask" completion:^{
NSLog(@"Task completed ..");
}];
More example with UIKit
classes methods.
更多UIKit
类方法示例。
[self presentViewController:viewController animated:YES completion:^{
NSLog(@"xyz View Controller presented ..");
// Other code related to view controller presentation...
}];
[UIView animateWithDuration:0.5
animations:^{
// Animation-related code here...
[self.view setAlpha:0.5];
}
completion:^(BOOL finished) {
// Any completion handler related code here...
NSLog(@"Animation over..");
}];
回答by pedrouan
Blocks: Obj-c
块:Obj-c
- (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block;
[object hardProcessingWithString:@"commands" withCompletion:^(NSString *result){
NSLog(result);
}];
Closures: Swift
关闭:斯威夫特
func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
...
completion("we finished!")
}
The completion closure herefor example is only a function that takes argument string and returns void.
例如,这里的完成闭包只是一个接受参数字符串并返回 void 的函数。
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
闭包是独立的功能块,可以在代码中传递和使用。Swift 中的闭包类似于 C 和 Objective-C 中的块以及其他编程语言中的 lambda。
Closures are first-class objects, so that they can be nested and passed around (as do blocks in Objective-C). In Swift, functions are just a special case of closures.
闭包是一流的对象,因此它们可以嵌套和传递(就像 Objective-C 中的块一样)。在 Swift 中,函数只是闭包的一个特例。
回答by Axel Guilmin
In short : Completion handlers are a way of implementing callback functionality using blocks or closures. Blocks and Closures are chunks of code that can be passed around to methods or functions as if they were values?(in other words "anonymous functions" which we can give names to and pass around).
简而言之:完成处理程序是一种使用块或闭包实现回调功能的方式。块和闭包是可以传递给方法或函数的代码块,就好像它们是值一样?(换句话说,我们可以命名并传递“匿名函数”)。
回答by Kirill Shur
I am hope this will help.
我希望这会有所帮助。
First Step:
第一步:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
-(void)InsertUser:(NSString*)userName InsertUserLastName:(NSString*)lastName widthCompletion:(void(^)(NSString* result))callback;
@end
Second Step :
第二步 :
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)InsertUser:(NSString *)userName InsertUserLastName:(NSString*)lastName widthCompletion:(void (^)(NSString* result))callback{
callback(@"User inserted successfully");
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self InsertUser:@"Ded" InsertUserLastName:@"Moroz" widthCompletion:^(NSString *result) {
NSLog(@"Result:%@",result);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end