Object existing after release
Can anyone explain to me why class object still exist after release. Here is the code
#import <Foundation/Foundation.h>
#import "MyClass.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
MyClass *开发者_开发问答class = [[MyClass alloc] init];
NSLog(@"%@", [class showMouse]);
NSLog(@"%@", [class printKbd]);
[class release];
NSLog(@"%@", [class printKbd]);
//still exist
[pool drain];
return 0;
}
Actually, dealloc does get called, you can check it by adding NSLog(@"dealloc called")
inside dealloc
method of MyClass
.
Why does it still work then? When an object gets released, the memory is not zeroed, it's simply marked as free to use by system. As a result, the code may still exist at the address of the pointer and *class
is simply a pointer to a block of memory. Here's the great SO answer that explains it in details.
Important thing to note is, should the program execution last any longer, the call to [class printKbd]
would most likely crash. That's why it's important to assign nil
to pointer, just to make sure we won't access the undefined part of memory.
精彩评论