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
- ios developer tiny share-20161108
- ios developer tiny share-20160628
- ios developer tiny share-20160629
- ios developer tiny share-20160630
- ios developer tiny share-20160701
- ios developer tiny share-20160704
- ios developer tiny share-20160705
- ios developer tiny share-20160706
- ios developer tiny share-20160707
- ios developer tiny share-20160708
- ios developer tiny share-20160711
- ios developer tiny share-20160712
- ios developer tiny share-20160713
- ios developer tiny share-20160714
- ios developer tiny share-20160715
- ios developer tiny share-20160718
- ios developer tiny share-20160719
- ios developer tiny share-20160720
- JavaScript内功功法AJAX的详解
- 释放Activator.CreateInstance创建的对象
- NIO浅析
- Swift enum
- (插件设计与简单应用)php中钩子(hook)的应用示例demo
- ios developer tiny share-20161108
- 汇编速查-函数调用
- jquery 去重
- JS判断浏览器,不考虑版本
- Xcode8.1不支持ios6.1真机
- 设计模式之工厂模式
- 基础知识:android 数据存储--->文件存储
- java中dynamic web project与web project 的区别
- SQL(十五)-Join类型