开发ociOS_Tips

Block 在Objective-C中的使用

2015-09-16  本文已影响186人  alvin_ding

转自How Do I Declare A Block in Objective-C? 结合实际使用的例子:

原文部分:

As a local variable:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

As a property:

@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

As a method parameter:

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

As an argument to a method call:

[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];

As a typedef:

typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};

This site is not intended to be an exhaustive list of all possible uses of blocks.
If you find yourself needing syntax not listed here, it is likely that a typedef would make your code more readable.
Unable to access this site due to the profanity in the URL? http://goshdarnblocksyntax.com is a more work-friendly mirror.

实例解析:

1.局部变量

void (^settingFontBlock)(NSMutableAttributedString *) = ^void (NSMutableAttributedString *attributedString) { //代码 };  

//后面的void可以省略, 参数attributedString 可写可不写,代码利用到了必须写

void (^settingFontBlock)(NSMutableAttributedString *) = ^(NSMutableAttributedString *) { //代码 };

2.属性

@property (nonatomic, copy) void (^settingFontBlock)(NSMutableAttributedString *);

3.方法的参数
- (void)insertAttributedText:(NSAttributedString *)text settingFontBlock:(void (^)(NSMutableAttributedString *attributedString))settingBlock;

4.方法调用
//returnType 为void,省略掉

[self insertAttributedText:attributedText settingFontBlock:^(NSMutableAttributedString *attributedString) {
    //代码实现
    //[attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedString.length)];
}];

//或者把1.定义的变量传进来使用

[self insertAttributedText:attributedText settingFontBlock:settingFontBlock];
上一篇下一篇

猜你喜欢

热点阅读