Objective-C iOS Development Using viewDidLoad or initWithCoder when setting Variables and Why?

╄→尐↘猪︶ㄣ 提交于 2019-12-23 20:35:17

问题


So it seems like I should be setting my member variables in viewDidLoad - but I am confused as to why setting these variables in initWithCoder fails, since both are called at the start of the program.

In particular I have a line of code:

[worldView setMapType:MKMapTypeSatellite];

In which worldView is a IBOutlet MKMapView object. It works under viewDidLoad, but not initWithCoder.


回答1:


The objects do not yet exist when initWithCoder is called, and they do when viewDidLoad is called. Check your initWithCoder method by logging out the value of worldView using something like:

NSLog(@"World View: %@", worldView);

and it will be nil. They will be initialized before the call to viewDidLoad, so you can set a property of that IBOutlet there.




回答2:


The outlets are not yet connected when initWithCoder is called. From the documentation:

During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type. Objects that conform to the NSCoding protocol (including all subclasses of UIView and UIViewController) are initialized using their initWithCoder: method.
...
After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects. It then calls the awakeFromNib method of the objects.

So awakeFromNib would be a suitable place for the custom setup of your UI elements.



来源:https://stackoverflow.com/questions/20480384/objective-c-ios-development-using-viewdidload-or-initwithcoder-when-setting-vari

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