简体   繁体   English

这会导致保留周期吗? (obj-c,示例代码)

[英]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 . SomeViewController具有someBlock作为属性,父视图控制器self提供newController ,而newControllersomeBlock正在访问父视图控制器的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. 不,这不会创建保留周期,因为您正在使用self的块是由SomeViewController保留的,而不是self / current view controller类本身。

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. 当您执行此代码时,someviewcontroller的块将在其范围内保留自身,而当您弹出someviewcontroller或该块被释放时,它将释放自身。

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. 您可以通过在SomeViewController和当前View Controller中的dealloc方法中添加NSLog语句来进一步验证这一点。

For details, refer to Apple Docs 有关详细信息,请参阅Apple Docs。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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