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?
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
Objectwere declared__block Someobject *Object, along with the expected effect (removing the ‘const’ of the block’s private reference, allowing the block to assign toObject), this autoretain behavior is also turned off. In that case retain/release is your responsibility again.)