IOS: the method returns a block, then the block is stored in an array, when should it be copied?

I have a method that returns a block and another method that uses a method:

- (MyBlock)blockForParameter:(id)param
{
    MyBlock theBlock = ^(){NSLog(@"Param: %@", param);};
    return theBlock;
}

- (void)methodUser
{
    MyBlock theBlock = [self blockForParameter:something];
    [self.allBlocks addObject:theBlock];
}

The question is when should a block be copied? Do I have to copy the block when I return it to blockForParameter, or do I need to copy it when I add it to the array?

thank

+5
source share
2 answers

Blocks must be copied if they "move to the area in which they were created," so you must copy the block to your method blockForParameterbefore returning it.

Edit: With ARC, this is no longer the case. See for example Objective-C: blocks in ARC and links in it:

  • .
  • .
+3

.

-blockForParameter: - . , . MRC , . ARC .

-methodUser ; . , (.. ). , , addObject:.

+1

All Articles