对于经常重新分配给新分配内存的实例变量,在 iPhone 应用程序中管理内存的正确方法是什么?
我无法弄清楚如何管理实例变量的内存,该实例变量需要在一段时间内保持当前状态,然后重新分配给新分配的内存。
以实例变量“importantData”为例:
-(void)Update
{
importantData = [[self getObject] retain];
}
- (SomeObject *)getObject
{
SomeObject *objInstance = [[SomeObject alloc] init];
[objInstance autorelease];
return objInstance;
}
在我的实际项目中,getObject 过程位于不同的类中,但我对其进行了简化,只是为了表达我的观点。 importantData 在更新调用之间必须保持有效。
每次调用 getObject 时,我都会分配新内存并将其分配给 importantData,对吗?我想我必须释放 importantData 之前指向的内存,对吗?我不确定如何在不泄漏内存或尝试引用已释放内存的情况下正确执行此操作。谢谢!
I'm having trouble figuring out how to manage memory for an instance variable that needs to maintain it's current state for a period of time, then be reassigned to newly allocated memory.
Take the following example for the instance variable "importantData".:
-(void)Update
{
importantData = [[self getObject] retain];
}
- (SomeObject *)getObject
{
SomeObject *objInstance = [[SomeObject alloc] init];
[objInstance autorelease];
return objInstance;
}
In my actual project, the getObject procedure is in a different class but I've simplified it just to get my point across. importantData must stay around be valid in between calls to Update.
Every time getObject is called, I'm allocating new memory and assigning it to importantData, correct? I figure I have to release the memory that importantData was pointing to before, right? I'm not sure how to do this properly without leaking memory or trying to reference deallocated memory. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需要更新为如下所示:
基本上,只需记住在分配新值之前释放即可。
You just need update to look like this:
Basically, just remember to release before you assign a new value.
您可以使用静态变量。
这将保留它直到应用程序存在。但是,如果您想使其无效或重新创建它,您可以添加一个方法,例如:
甚至
您现在可以在
SomeObject
的类和实例方法中使用importantObject
,或者获取它通过SomeObject
的类方法 getter 从其他类获取。You could use a static variable.
This will keep it around until the app exists. But if you want to invalidate or recreate it you could add a method like:
Or even
And you can now use
importantObject
inSomeObject
's class and instance methods, or fetch it from other classes viaSomeObject
's class method getter.