完成处理程序和块之间的区别:
当我在Swift
和Objective-C
使用它时,我被完成处理程序和块搞砸了。 当我在谷歌上搜索Swift
块时,它显示完成处理程序的结果! 有人可以告诉我完成处理程序和块与Swift
和Objective-C
什么区别?
在这里,您可以轻松区分块和完成处理程序,实际上两个块都是块,请参阅下面的详细信息。
块:
块是添加到C,Objective-C和C ++的语言级function,它允许您创建不同的代码段,这些代码段可以传递给方法或函数,就像它们是值一样。 块是Objective-C对象,这意味着它们可以添加到NSArray或NSDictionary等集合中。
- 它们可以在以后执行,而不是在执行它们已经实现的范围的代码时执行。
- 它们的使用最终导致更清晰,更整洁的代码编写,因为它们可以用于代替委托方法,只在一个地方编写而不会传播到许多文件。
语法: ReturnType(^ blockName)(参数) 参见示例 :
int anInteger = 42; void (^testBlock)(void) = ^{ NSLog(@"Integer is: %i", anInteger); // anInteger outside variables }; // calling blocks like testBlock();
阻止参数:
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);
完成处理程序:
而完成处理程序是使用块实现回调function的一种方法(技术)。
完成处理程序只不过是一个简单的块声明,作为参数传递给需要在以后进行回调的方法。
注意: 完成处理程序应始终是方法中的最后一个参数。 方法可以包含任意数量的参数,但始终将完成处理程序作为参数列表中的最后一个参数。
例:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback; // calling [self beginTaskWithName:@"MyTask" completion:^{ NSLog(@"Task completed .."); }];
使用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.."); }];
简而言之:完成处理程序是一种使用块或闭包实现回调function的方法。 块和闭包是代码块,可以传递给方法或函数,就好像它们是值(换句话说,“匿名函数”,我们可以给出名称和传递)。
块 : Obj-c
- (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block; [object hardProcessingWithString:@"commands" withCompletion:^(NSString *result){ NSLog(result); }];
闭包 : 斯威夫特
func hardProcessingWithString(input: String, completion: (result: String) -> Void) { ... completion("we finished!") }
例如, 完成闭包只是一个带参数字符串并返回void的函数。
闭包是自包含的function块,可以在代码中传递和使用。 Swift中的闭包类似于C和Objective-C中的块以及其他编程语言中的lambdas。
闭包是第一类对象,因此它们可以嵌套并传递(与Objective-C中的块一样)。 在Swift中,函数只是闭包的一个特例。
我希望这会有所帮助。
第一步:
#import @interface ViewController : UIViewController -(void)InsertUser:(NSString*)userName InsertUserLastName:(NSString*)lastName widthCompletion:(void(^)(NSString* result))callback; @end
第二步 :
#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