如果我以编程方式创建视图并将它们添加到视图层次结构中,为什么它们需要是强引用?

Sam*_*D20 2 objective-c ios automatic-ref-counting

我有一个简单的视图控制器,其中有几个视图对象,我以编程方式创建.这是ViewController.h的一部分:

@property (nonatomic, strong) UIScrollView* scrollView;
@property (nonatomic, strong) UILabel* listingTitle;
@property (nonatomic, strong) MKMapView* listingMap;
@property (nonatomic, strong) UILabel* listingPrice;
Run Code Online (Sandbox Code Playgroud)

如您所见,它们都是强有力的参考.如果我将其中任何一个弱引用,ARC就会释放它们.据我所知,如果它们被添加到视图层次结构中,它们就不会解除分配,因为它们归层次结构中的下一级视图所有.对于其中一个,作为一个例子,我在这里这样做:

self.listingTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, self.view.frame.size.width - 10, 60)];
[self.scrollView addSubview:listingTitle]; 
Run Code Online (Sandbox Code Playgroud)

但同样,如果我给它一个弱引用,它会解除分配.这是为什么?

yur*_*ish 6

问题是因为您创建子视图并立即为弱属性分配引用.因此,在将子视图添加到超级视图之前,会立即取消分配子视图.如果你想拥有弱属性,你可以这样做:

UIView *mySubview = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, self.view.frame.size.width - 10, 60)];
[self.scrollView addSubview: mySubview];
self.listingTitle = mySubview; 
Run Code Online (Sandbox Code Playgroud)