Copying blocks (ie: copying them to instance variables) in Objective-C

后端 未结 4 1308
[愿得一人]
[愿得一人] 2020-12-08 21:31

I\'m trying to understand blocks. I get how to use them normally, when passed directly to a method. I\'m interested now in taking a block, storing it (say) in an instance va

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 22:04

    Copy a block when you want it to stay around. Autorelease or release it when you're through with it. Retain it if you need a long way to spell /* NOP */.

    @interface Foo : FooSuper {}
    @property(copy) int (^storedBlock)(int);
    @end
    
    @implementation Foo
    @synthesize storedBlock = mStoredBlock;
    
    - (void)setupStoredBlock {
        self.storedBlock = ^{/*...*/};
        // or: mStoredBlock = [^{/*...*/} copy];
        // but this simple implementation violates the atomicity contract
    }
    
    - (void)runStoredBlock {
        int result = self.storedBlock(5);
        NSLog(@"%s: result = %d", __func__, result);
    }
    @end
    

提交回复
热议问题