简体   繁体   中英

Why do variables initialized in viewDidLoad not retain value in Objective-C?

I have a class I wrote called Location that just holds some strings. I'm using two instances of that class in a view controller, and when I initialize the two variables in viewDidLoad, they work fine for that method, but then when I try to use them later they are null. I have them set as retained properties. I have tested them and know that they are initialized for viewDidLoad (I use their fields in the view). Do I have to do something special in the Location class to make sure they don't get released? When I re-initialize them in a different method, everything runs smoothly.

Instance variables properly initialized in viewDidLoad should retain values normally just like they would in any other method. A coding error may cause the issue you are describing, eg if you have local variables in viewDidLoad hiding identically named instance variables.

you (or the event loop) is probably releasing the objects you are initializing after viewDidLoad is complete since they are autoreleased or something. To prevent that, make the variables in question properties on the class with the "retain" attribute and set them to nil on dealloc.

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