Daniel
Daniel

Reputation: 31579

Tying an object to a block

I have the following object:

Someobject *Object = [[Someobject alloc] init];

void (^Block)() = ^()
{
    Use(Object);
};

DoSomethingWith(Block);

The block is copied in DoSomethingWith and stored somewhere. it might either not be called, called once or called multiple times. I want to tie Object with the block so whenever the block or any of its copies is released, Object is released, and whenever the block or any of its copies is retained or copied, Object will be retained.
Is there a way to do so?

Upvotes: 1

Views: 57

Answers (1)

rgeorge
rgeorge

Reputation: 7327

Change your first line to [[[Someobject alloc] init] autorelease] and you're done.

Blocks retain objects declared without and referenced within their body, and release them on release. So will the copy of the block made within DoSomethingWith. Assuming that copy eventually gets released there's no leak. It's pretty cool.

(Exception: if Object were declared __block Someobject *Object, along with the expected effect (removing the 'const' of the block's private reference, allowing the block to assign to Object), this autoretain behavior is also turned off. In that case retain/release is your responsibility again.)

Upvotes: 3

Related Questions