为什么在 viewDidLoad 中初始化的变量在 Objective-C 中不保留值?
我写了一个名为 Location 的类,它只包含一些字符串。我在视图控制器中使用该类的两个实例,当我初始化 viewDidLoad 中的两个变量时,它们对于该方法工作得很好,但是当我稍后尝试使用它们时,它们为空。我将它们设置为保留属性。我已经测试了它们并知道它们是为 viewDidLoad 初始化的(我在视图中使用它们的字段)。我是否必须在 Location 类中做一些特殊的事情以确保它们不会被释放?当我用不同的方法重新初始化它们时,一切都会顺利进行。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 viewDidLoad 中正确初始化的实例变量应正常保留值,就像在任何其他方法中一样。编码错误可能会导致您所描述的问题,例如,如果 viewDidLoad 中有局部变量隐藏相同名称的实例变量。
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, e.g. if you have local variables in viewDidLoad hiding identically named instance variables.
您(或事件循环)可能会在 viewDidLoad 完成后释放您正在初始化的对象,因为它们是自动释放的或其他什么。为了防止这种情况发生,请使用“retain”属性在类上设置相关变量的属性,并在 dealloc 时将它们设置为 nil。
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.