Objective-C自动释放池不释放对象 [英] Objective-C autorelease pool not releasing object

查看:86
本文介绍了Objective-C自动释放池不释放对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Objective-C还是陌生的,正在阅读内存管理.我试图在NSAutoreleasePool上玩一些,但是不知何故它不会释放我的对象.

I am very new to Objective-C and was reading through memory management. I was trying to play around a bit with the NSAutoreleasePool but somehow it wont release my object.

我有一个带有setter和getter的类,它基本上设置了NSString * name.释放池后,我尝试对对象进行NSLog,它仍然可以工作,但我想应该不可以?

I have a class with a setter and getter which basically sets a NSString *name. After releasing the pool I tried to NSLog the object and it still works but I guess it should not?

@interface TestClass : NSObject
{
    NSString *name;
}

- (void) setName: (NSString *) string;
- (NSString *) name;


@end

@implementation TestClass   

- (void) setName: (NSString *) string
{
        name = string;
}  

- (NSString *) name
{
    return name;
}

@end

int main (int argc, const char * argv[]) {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

TestClass *var = [[TestClass alloc] init];

[var setName:@"Chris"];
[var autorelease];
[pool release];

// This should not be possible?
NSLog(@"%@",[var name]);


return 0;
}

推荐答案

您的代码有几个问题.首先,您既不执行copy也不执行retain存储在name实例变量中的字符串.因此,如果该字符串是由存储在属性中的任何人释放的,则将留下一个悬挂的引用.你应该做

Your code has several problems. First, you do neither copy nor retain the string stored into the name instance variable. So, if the string is released by whoever stored it into the property, you are left with a dangling reference. You should do

- (void) setName: (NSString*) aName {
    if( name != aName ) {
        if( name ) [name release];
        name = [aName retain];    // or copy
    }
}

或从一开始就使用属性.

or use properties right from the start.

此外,如果将对象引用保留在实例变量中,则应提供dealloc方法的正确定义:

Also, if you keep object references in instance variables, you should provide a proper definition of the dealloc method:

- (void) dealloc {
    self.name = nil;
    [super dealloc];
}

最后,仅仅因为对象已被释放,并不意味着前一个实例的内存无效.您的原始程序很可能在悬空引用(var)上调用一个方法,碰巧在这里碰巧可以正常工作. (特别是to(auto)release不会自动将引用设置为nil.)

Finally, just because an object has been deallocated, does not mean, that the memory of the former instance is invalidated. Your original program is most likely calling a method on a dangling reference (var), which happens to work by sheer luck here. (In particular, to (auto)release does not automatically set the reference to nil).

这篇关于Objective-C自动释放池不释放对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆