简体   繁体   中英

Will this cause a retain cycle? (obj-c, sample code)

SomeViewController *newController = [SomeViewController new];
[newController setSomeBlock:^{
   [self.someProperty doSomething];
}];
[self presentViewController:newController animated:YES completion:nil];

SomeViewController has someBlock as a property, parent view controller self presents newController , and newController 's someBlock is accessing the parent view controller's self.someProperty .

Will this cause a retain cycle?

NO this won't create a retain cycle because the block you are using self in, is retained by SomeViewController not the self/current view controller class itself.

When you execute this code the someviewcontroller's block will retain the self during its scope and when you pop that someviewcontroller or that block gets deallocated it would release the self back.

A retain cycle is only caused when two objects retain each other, for example, in this case:

SomeViewController *newController = [SomeViewController new];
[newController setSomeBlock:^{
    [newController doSomething];
}];
[self presentViewController:newController animated:YES completion:nil];

You can further verify this by adding an NSLog statement to dealloc method in SomeViewController and current View Controller.

For details, refer to Apple Docs

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