gpt4 book ai didi

Objective-C:理解 ARC

转载 作者:行者123 更新时间:2023-12-01 19:17:34 25 4
gpt4 key购买 nike

我是 Objective-C 的新手。这是我对一些用于以编程方式添加 subview 的简单代码的 ARC 的理解(如在评论中)。如果我错了,请纠正我。特别是在这个声明中:

"ViewController points to myView weakly" ACTUALLY means that _myView (ViewController's ivar) points to a UIView object weakly


// _myView stores a pointer pointing to a UIView object
// "ViewController points to myView weakly" ACTUALLY means that _myView (ViewController's ivar) points to a UIView object weakly

@interface ViewController ()
@property (nonatomic,weak) UIView *myView;
@end

@implementation
@synthesize myView = _myView;
@end

- (void)viewDidLoad
{
[superviewDidLoad];
CGRect viewRect = CGRectMake(10, 10, 100, 100);

// a UIView object is alloc/inited
// mv is a pointer pointing to the UIView object strongly (hence the owner of it)
UIView *mv = [[UIView alloc] initWithFrame:viewRect];

// _myView points to the UIView object weakly
// Now the UIView object now have two pointers pointing to it
// mv points to it strongly
// _myView points to it weakly, hence NOT a owner
self.myView = mv;

// self.view points to the UIView object strongly
// Now UIView object now have THREE pointer pointing to it
// Two strong and one weak
[self.view addSubview:self.myView];
}

// After viewDidLoad is finished, mv is decallocated.
// Now UIView object now have two pointer pointing to it. self.view points to it strongly hence the owner, while _myView points to it weakly.

最佳答案

你大部分是正确的,除了这句话:

After viewDidLoad is finished, mv is decallocated.



那就是你错了。请记住,对象的解除分配只有在每个人 retain 时才会发生。是对象 release是的。因此,虽然你有 release 'd 临时变量 mv , 您还有另一个来源保留它: self.view.subviews .一次 mv从 subview 数组中删除,可以正确清理, _myView设置为 nil ,并且您没有更多的泄漏。

关于Objective-C:理解 ARC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12197095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com