Objective C 泄漏 NSNumber 被保留
我的应用程序使用 GPS 并在每次更新 GPS 时分配一个 NSNumber 实例变量,并且在发布前的最后一点测试中,我发现它泄漏了很多。我相当确定我知道哪些线路导致了泄漏,但我不知道如何解决它。
latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];
这条线在我的 GPS 更新方法中并且定期运行。 Latitude是一个实例变量,当我删除retain时,我无法再在我需要的其他方法中访问该变量。我在 dealloc 方法中释放了变量,但这似乎没有做任何事情。
我了解分配释放范例,但我仍然不确定如何解决这个问题。
My application uses GPS and assigns an NSNumber instance variable every time the GPS is updated and in my last bit of testing before release, I've discovered that it leaks a lot. I'm fairly certain I know which lines are contributing to the leak, but I can't figure how to solve it.
latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];
This line is in my GPS update method and is run regularly. Latitude is an instance variable, and when I remove the retain, I can no longer access the variable in the other methods I need. I have the variable released in the dealloc method, but that doesn't seem to do anything.
I understand the alloc-release paradigm, but I'm still not sure how to fix this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在设置之前,必须释放之前保留的值。否则,当您分配新指针时,先前释放的对象没有任何引用它的对象,并且永远无法释放它。
为了轻松做到这一点,我建议将其设置为
@property
并使用self.latitude = [NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]];
。请注意,赋值中不再使用保留。这是假设您的属性设置了retain
标志,并为您保留它。即
@property(非原子,保留)NSNumber *纬度
Before setting it, you must release the previously retained value. Otherwise, when you assign the new pointer, the previous object which is released has nothing referencing it and it can never be released.
To do this easily, I recommend setting it as a
@property
and usingself.latitude = [NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]];
. Notice that the retain is no longer used in the assignment. This is assuming your property is set up with theretain
flag, and retains it for you.I.e.
@property (nonatomic, retain) NSNumber *latitude
在没有看到代码的其余部分的情况下,很难准确地说出应该如何解决这个问题,但一个好的第一个方法可能是尝试自动释放它,如下所示:
另一个要考虑的事情是将纬度设置为 @property 并将其设置为保留。这样,当你设置它时,它就会释放之前的值。同样,如果不知道如何使用纬度,就很难为您指明一个可靠的方向。
Without seeing the rest of your code its tough to say exactly how you should fix this, but a good first approach might be to try autoreleasing it like:
The other thing to consider is making latitude a @property and set it to retain. This way, when you set it, it will release the previous value. Again, without knowing how you're using latitude its hard to point you in a solid direction.