简体   繁体   中英

IOS block not retain self?

Im new to the block programming in ios, Ive read many guides and they say, things get retained in a block, and I write a demo to test the retain cycle they mentioned.

header file:

typedef NSString* (^MyBlock)(void);

@interface DetailViewController : UIViewController <UISplitViewControllerDelegate>
{

    UIView * testView;

    SubDetailViewController * tSubDetailViewController;

    NSMutableArray * array;

    MyBlock block1;

}

m file: in viewDidLoad :

array = [[NSMutableArray alloc] init];

block1 = ^(void){

    [array addObject:@"23"];

    [self btn2Touch:nil];

    return @"3";
};
NSLog(@"self after block retainCount -> %d",self.retainCount);
NSLog(@"array after block  retainCount -> %d",array.retainCount);

//self.block1();

[array release];

I thought the array and self will be retained, retatinCount +1; but whether I do self.block1(), or not, the retainCount not +1, everything seems fine, array could be released,when pop the view controller, self release normally.

do I miss something with guides? so curious abt this situation. anyone could give me a code of retain cycle with block?

Blocks retain their captured variables when the block is copied. Since you are using MRC, the compiler does not do anything automatically. You are assigning the block literal directly to the instance variable block1 (not through a property or something), so no copying is done.

This is incorrect use of blocks, because any time where you store a block (eg in an instance variable) in a place that will out-live the current scope, you must copy it. Block literals are only valid in the scope they are defined in. This is because blocks may start out on the stack, and must be copied to be moved into the heap; otherwise, they are destroyed at the end of the scope. So if you try to use the block pointed to by block1 after this function is done, bad things will probably happen.

So if you had used blocks correctly, you would have copied the block, thus the block would retain self . In addition, as an instance variable, the block should also be retained by self , in order to follow memory management rules. So you have a retain cycle.

This block is in stack, a block in stack will not retain object in its body. Instead, a block in heap, will retain object in its body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM