【问题标题】:Difference Between Completion Handler and Blocks : [iOS]完成处理程序和块之间的区别:[iOS]
【发布时间】:2017-01-29 07:13:36
【问题描述】:

当我在SwiftObjective-C 中使用它们时,我对完成处理程序和块都感到困惑。当我在 google 上的 Swift 中搜索块时,它会显示完成处理程序的结果!有人能告诉我关于 SwiftObjective-C 的完成处理程序和块之间有什么区别吗?

【问题讨论】:

  • 所有完成处理程序都是块,但并非所有块都是完成处理程序。

标签: ios objective-c swift block completionhandler


【解决方案1】:

简而言之:完成处理程序是一种使用块或闭包实现回调功能的方法。块和闭包是可以传递给方法或函数的代码块,就好像它们是值一样(换句话说,我们可以命名和传递的“匿名函数”)。

【讨论】:

    【解决方案2】:

    Obj-c

    - (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block;
    
    [object hardProcessingWithString:@"commands" withCompletion:^(NSString *result){
        NSLog(result);
    }];
    

    闭包Swift

    func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
        ...
        completion("we finished!")
    }
    

    例如,这里的完成闭包只是一个接受参数字符串并返回 void 的函数。

    闭包是可以传递的独立功能块 周围并在您的代码中使用。 Swift 中的闭包类似于块 在 C 和 Objective-C 以及其他编程语言中的 lambdas 中。

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

    闭包 是一流的对象,因此它们可以嵌套和传递 (就像 Objective-C 中的块一样)。在 Swift 中,函数只是一个特殊的 关闭的情况。

    【讨论】:

      【解决方案3】:

      在这里您可以轻松区分块和完成处理程序,实际上两者都是块,请参阅下面的详细信息。

      块:

      块是添加到 C、Objective-C 和 C++ 的语言级功能,它允许您创建不同的代码段,这些代码段可以像值一样传递给方法或函数。块是 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);
      

      完成处理程序:

      而完成处理程序是一种使用块实现回调功能的方法(技术)。

      完成处理程序只不过是一个简单的块声明,作为参数传递给需要稍后进行回调的方法。

      注意:完成处理程序应该始终是方法中的最后一个参数。一个方法可以有任意多个参数,但始终将完成处理程序作为参数列表中的最后一个参数。

      例子:

      - (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..");
                           }];
      

      【讨论】:

        【解决方案4】:

        我希望这会有所帮助。

        第一步:

        #import <UIKit/UIKit.h>
        
        @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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-05-10
          • 2015-04-06
          • 1970-01-01
          • 2013-12-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多