目录

在 ObjC 中如何定义 Block

来自一个神奇的域名

http://fuckingblocksyntax.com/

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
@property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
- (void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes))blockName;
[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};

It is still a good idea to declare block properties as having copy semantics since a block assigned to a strong property will in fact be copied.

Apple recommends this as well:

You should specify copy as the property attribute, because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior.

人生如逆旅,我亦是行人
人生如逆旅,我亦是行人

Комментарии