0

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;
}
jingo
  • 1,084
  • 5
  • 14
  • 23
  • 1
    When you call `release` object you only tell to it that it's not needful anymore. It will be released in some time later – Nekto Oct 14 '11 at 07:25

1 Answers1

2

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.

Community
  • 1
  • 1
Bartosz Ciechanowski
  • 10,293
  • 5
  • 45
  • 60