Block’s trick

Xcode has a built-in Block Snippet, just type inline and it will appear.

C Inline Block as Variable – Save a block to a variable to allow reuse or passing it as an argument.

returnType(^blockName)(parameterTypes) = ^(parameters){
    statements 
};Copy the code

But this is actually not the way to define a complete Block, if you want to define a complete Block.

returnType(^blockName)(parameterTypes) = ^returnType(parameters){
    statements 
};Copy the code

Block Common Scenarios

1. Block Is used temporarily

[myArray enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL*stop) {    
    [self doSomethingWith:object];
}];
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(idobj, NSUInteger idx, BOOL *stop) {    
    [self doSomethingWith:object];
}];Copy the code


NSArray* enumerateArray = @[@"1 🐶"The @"2 🐱"The @"3 🐭"The @"Four 🐹"The @"Five 🦊" ]; 
[enumerateArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    NSLog(@"% @ % @", obj, [NSThread currentThread]); 
}];Copy the code

It is important to note that this option can be executed concurrently or in reverse.

NSEnumerationOptions
    -> NSEnumerationConcurrent
    -> NSEnumerationReverseCopy the code

NSEnumerationConcurrent takes special note

The order of calls is nondeterministic and undefined; This flag is a hint that may be ignored in some cases; Block code must be secure because it may be called concurrently.



2. Blocks are used for short periods, but are stored (e.g., they need to be stored, but are called only once, or have a completion period. For example, an animation of UIView, after the animation is done, you need to notify the outside world with a block. Once the block is called, the block can be deleted.

[UIView animateWithDuration:0.2 animations:^{// animations go here}]; [UIView animateWithDuration:0.2 animations:^{// animations go here} completion:^(BOOL finished) {// Block Fires WHEN animation has finished } ]; [UIView animateKeyframesWithDuration: delay 0.2:0.0 options: UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{ // animations go here } completion:^(BOOL finished) { // block fires when animaiton has finished } ];Copy the code


3. Long term use of a Block (eg as an attribute)

// block instead of delegate- (void) viewDidLoad {
    [super viewDidLoad];
    Person* person = [[Person alloc] init];
    person.run = ^(){
        NSLog(@ "running 🏃 ‍ came ️ 🏃 ‍ came ️"); }; _p = person; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.p.run();
}Copy the code