UILabel 在运行时更改,管理更改字符串的内存
我有几个标签在游戏过程中用作玩家的 HUD。我会经常更新这些标签,以便玩家获得最新信息。问题是我一直用来
uiLabel.text = [NSString stringWithFormat:@"%3.0f", value];
传递标签应该具有的新值。然而,我注意到这里有一些软内存泄漏。由于我每秒多次执行此更新,并且这会创建一个设置为自动释放的字符串,因此我最终占用的内存超出了我的需要。并保留它,因为视图不会消失。
我还尝试显式分配和释放字符串,例如:
NSString* value = [[NSString alloc] initWithFormat: @"%3.0f", value];
uiLabel.text = value;
[value release];
但是,我发现这似乎会导致相同的事情,但速度更快,尽管我不知道为什么。在这种情况下,我认为根本不应该有字符串等待释放,因为我如此明确地驳回了它们。
有人能看到我在这里所做的事情,而我显然没有看到吗?有没有更好/更优选的方法来处理这个问题?一些粗略的搜索对我来说并没有什么结果。
I have a couple labels I am using as a HUD for the player during a game. I am updating these labels frequently, so that the player has up-to-date information. The problem is is that I've been using
uiLabel.text = [NSString stringWithFormat:@"%3.0f", value];
to pass the new value that the label should have. I have noticed, however, that I have something of a soft-memory leak here. As I'm doing this update multiple times a second and this creates a string that is set to autorelease, I'm ending up taking more memory than I need. And keeping it, as the view is not going away.
I also tried to alloc and release strings explicitly, such as:
NSString* value = [[NSString alloc] initWithFormat: @"%3.0f", value];
uiLabel.text = value;
[value release];
However, I find that this seems to cause the same thing, but faster, though I don't know why. In this situation I would have thought there should never be strings sitting around waiting to be released at all, since I'm so explicitly dismissing them.
Can anyone see what I'm doing here that I obviously am failing to see? Is there a better/more preferred way to handle this? Some cursory searching didn't turn up much for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你没有做任何不寻常的事情。即使:
每次代码将控制权返回给运行循环时,自动释放池都会被耗尽(因此至少与您看到 UI 更新的频率一样)。如果您发现内存分配不断增加,您应该看看其他地方。
You're not doing anything out of the ordinary. Even with:
the autorelease pool gets drained every time your code returns control to the run loop (so at least as often as you see the UI updating). If you see growing memory allocations, you should look elsewhere.