Objective-C autorelease pool not releasing object

只愿长相守 提交于 2019-12-01 21:54:52

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.

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];
}

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).

When you release the pointer var, you're telling the OS that the memory it pointed to is available to be reallocated. The pointer still points to that memory, and until it gets reallocated it still contains the remains of your object. Once it gets reallocated, trying to call the name method will no longer work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!