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")insidedeallocmethod ofMyClass.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
*classis 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 assignnilto pointer, just to make sure we won’t access the undefined part of memory.