简体   繁体   中英

Alloc-init an object in a UIStoryboard

Consider a situation where you have an object in a storyboard file linked up to an IBOutlet , such as the following.

@property (nonatomic, strong) IBOutlet UIImageView *imageView;

Left to its own devices, the ViewController will happily load and display the correct image inside the correct frame, etc, as determined in Interface Builder. However, if the following code is added to the View Controller's viewDidLoad method, an (apparently) identical outcome is achieved.

- (void)viewDidLoad {
    _imageView = [[UIImageView alloc] init];
    //...
}

Does this mean the programmatic alloc-initing of IBOutlets is completely optional? Or is the addition of this line achieving a slightly different outcome?

I'm asking because I have always added the alloc-init in the implementation, then in my latest project I forgot about it, and to my surprise, it still worked exactly as intended.

A storyboard or xib file is a serialisation of the objects contained within. When the storyboard is loaded, all of the objects are instantiated (using initWithCoder: , since we are deserialising them). This does the same job as allo/init, with the addition of setting all of the properties of the object that are defined in the xib.

The xib contains enough information about your image view to fully create it. If you then alloc/init a new image view and assign it to the variable that was used for the outlet, you are just replacing the object that was created from the storyboard, which is pretty pointless, since your outlet now points to nothing on the screen.

In summary - alloc/init ing every outlet isn't optional , it's wrong .

当您将一个对象添加到NIB时,该对象的生命周期完全由UIViewController(或子类)和ARC引用控制,默认情况下它是弱的,因为ViewController会在加载该对象时正确处理该对象的alloc,init和release视图,因此您所做的就是将ARC参考更改为“强”,因此在引用该对象后不会立即释放该对象,它可以像您尝试的那样工作,但从理论上讲,您将在Interface Builder中创建该对象并结束如果您未设置任何框架或未将其添加到任何视图,并且未在该对象的后面进行任何引用,则ARC将释放该对象,并以在其中创建的图像视图结束Inteface Builder,但是在您将_imageView引用到刚创建的新[[UIImageView alloc] init]时没有指向它的任何指针。

If you are using Xcode 4.4 it will automatically synthesize the properties for you. It may be this you are experiencing? Ref

Alloc/init of an object in storyboard is basically a mistake.

When the view is loaded, all the subviews will be initialized and loaded automatically. If you initialize it again, there will be another instance created and the previous instance of the object goes unused.

In fact, in order to make the recently initialized object instance to work properly, you have to add the instance (in your case instance of UIImageView) as subview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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