Nicolas
Nicolas

Reputation: 795

Access Stack Block from within Block using ARC in Objective-C

My question regards blocks in Objective-C: Assume the following situation (with ARC enabled):

typedef NSString*(^MyBlockType)();
typedef NSString*(^MyReturnBlockType)(MyBlockType);

- (MyReturnBlockType) foo: (MyBlockType) block
{
    return ^NSString*(MyBlockType someBlock) {
        return someBlock();
    };
}

The parameter block that is received by the method foo: is used within the block that is returned by the method. However, who keeps a strong reference to the block? Should foo: copy the block before returning the MyReturnBlockType-block? Any insight would be appreciated.

Upvotes: 1

Views: 93

Answers (1)

newacct
newacct

Reputation: 122509

  1. The parameter block is not used anywhere in your code.

  2. Let's supposed that you meant to use block inside someBlock. Variables of object pointer type captured by a block are retained when the block is copied. Furthermore, variables of block pointer type captured by a block are copied when the block is copied. So, when someBlock is copied, block will be copied.

  3. In ARC, a stack block that is returned directly is automatically copied before returning. Thus, someBlock, and also block, will be caused to be copied.

  4. No, foo: does not need to explicitly copy block, because it is not doing anything to explicitly store it (in an instance variable or something).

Upvotes: 1

Related Questions