ios developer tiny share-20161108

来源:互联网 发布:ACER windows激活 编辑:程序博客网 时间:2024/05/23 14:56

今天继续讲Objective-C的Block,讲Block作为方法的参数,按照惯例,一般放到最后一个。另外,讲下使用typeof来定义Block,使得Block在语法上更加简洁、易读。


下面是ios reference官方的讲解:


A Block Should Always Be the Last Argument to a Method

It’s best practice to use only one block argument to a method. If the method also needs other non-block arguments, the block should come last:

- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;

This makes the method call easier to read when specifying the block inline, like this:

[self beginTaskWithName:@"MyTask" completion:^{NSLog(@"The task is complete");}];


Use Type Definitions to Simplify Block Syntax


If you need to define more than one block with the same signature, you might like to define your own type for that signature.

As an example, you can define a type for a simple block with no arguments or return value, like this:

typedef void (^XYZSimpleBlock)(void);

You can then use your custom type for method parameters or when creating block variables:

XYZSimpleBlock anotherBlock = ^{...};

- (void)beginFetchWithCallbackBlock:(XYZSimpleBlock)callbackBlock {    ...    callbackBlock();}

Custom type definitions are particularly useful when dealing with blocks that return blocks or take other blocks as arguments. Consider the following example:

void (^(^complexBlock)(void (^)(void)))(void) = ^ (void (^aBlock)(void)) {    ...    return ^{        ...    };};

The complexBlock variable refers to a block that takes another block as an argument (aBlock) and returns yet another block.

Rewriting the code to use a type definition makes this much more readable:

XYZSimpleBlock (^betterBlock)(XYZSimpleBlock) = ^ (XYZSimpleBlock aBlock) {    ...    return ^{        ...    };};


0 0