Creating views programmatically Strong Vs Weak subviews in controller

扶醉桌前 提交于 2019-12-03 09:09:37
Neil

Your cityLabel property can be weak, but you must add it to the view hierarchy before you can assign the property or assign it to a standard (strong reference) variable.

What is going on is that you're creating a UILabel, then assigning it to a property which assumes no ownership of it (weak). After you've gone past the self.cityLabel = [[UILabel alloc] ... line, the UILabel has already been deallocated and the cityLabel property is nil.

This will correctly do what you intend:

UILabel *theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 80.0f, 30.0f)];
self.cityLabel = theLabel;
[addressView addSubview:theLabel];

The variable theLabel will retain the UILabel during for scope of createCityLabel: and adding the UILabel as a subview to a view that is part of the View Controller's view will retain it for the life of the view controller (unless you remove the UILabel from the view or any of the UILabel's parent views)).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!