以编程方式创build视图强Vs控制器中的弱子视图

我正在写一个使用Xcode 5.1.1的小型testing程序,用于iOS 7.1。 我没有使用Xib或Storyboard。 一切都以编程方式完成。 在AppDelegate.m中,我创build了一个TestViewController的实例,并将其设置为窗口的rootViewController。 在TestViewController.m中,我重写了“loadView”来创build和分配控制器的主视图。

TestViewController.h -------------------- @interface TestViewController : UIViewController @property (nonatomic, weak) UILabel *cityLabel ; @end TestViewController.m -------------------- @implementation TestViewController - (void)loadView { UIView *mainView = [[UIView alloc] init] ; self.view = mainView ; } - (void) viewDidLoad { UIView *addressView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)] ; [self.view addSubview:addressView] ; [self createCityLabel:addressView] ; } - (void) createCityLabel:(UIView *)addressView { // Warning for below line - Assigning retained object to weak property... self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 30)] ; [addressView addSubview:self.cityLabel] ; } @end 

根据我的理解,所有权如下

testViewController —(strong) – > self.view – (strong) – > addressView – (strong) – > self.cityLabel的对象。

因此,self.cityLabel可能是对其目标对象的弱引用

self.cityLabel – (weak) – > self.cityLabel的对象。

我在这里也遇到类似问题的其他问题。 在任何地方,build议将IBOutlet属性保留在ViewController中“弱”(虽然不是必须的,除非有循环引用)。 控制器的主要观点只保留强有力的参考。

不过,我正在接受createCityLabel函数的警告。 如果我删除“弱”属性,这将消失。 这真是令人困惑。 是否build议让奥特莱斯弱,仅适用于使用Xib / Storyboard创build的应用程序?

您的cityLabel属性可能很弱,但您必须将其添加到视图层次结构中,然后才能分配属性或将其分配给标准(强引用)variables。

发生了什么事是你正在创build一个UILabel ,然后把它分配给一个不承担它的属性(弱)。 在通过self.cityLabel = [[UILabel alloc] ...行之后, UILabel已经被释放, cityLabel属性为零。

这将正确地做你想要的:

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

variablestheLabel将在theLabel保留UILabel createCityLabel:并且将UILabel作为子视图添加到作为View Controller视图一部分的视图将在视图控制器的整个生命周期中保留它(除非从视图中移除UILabel或任何UILabel的父视图))。