如果使用Block在Objective-C和Swift中

A Block in Objective-C?

1.局部变量:
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

2.声明:
@property (nonatomic, copy,) returnType (^blockName)(parameterTypes);

3.方法中使用:
- (void)someMethodABlock:(returnType (^)(parameterTypes))blockName;

4.方法调用时参数:
[Object someMethodABlock:^returnType (parameters) {...}];

5.别名:
typedef returnType (^TypeName)(parameterTypes);TypeName blockName = ^returnType(parameters) {...};
example:

1.typedef void (^completitionBlock) (id obj, NSError * err);

2.-(id)initWithRequest:(NSURLRequest *)req completitionBlock:(completitionBlock)block;

-(id)initWithRequest:(NSURLRequest *)req completitionBlock:(void (^) (id obj, NSError * err) completitionBlock ;

3.@property (nonatomic,copy)void (^completition) (id obj, NSError * err);

A Block in Swift?

1.别名
typealias blockName = (parameters) -> returnType

2. 方法
func someMethodABlock(completion:((parameters) -> returnType)!)

3.声明
var block:blockName
var block:((parameters) -> returnType)?
example:

1.typealias completionHandler = (NSDictionary?,NSError?) -> Void

2. func authorizeHealthKit(completion:((success:Bool, error:NSError!) -> Void)!)

3. var block:completionHandler

4.  var block:((dic:NSDictionary ,error:NSError) -> Void)?

    原文作者:Ylang
    原文地址: https://www.jianshu.com/p/1cde3a6b07b9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞