Why the Objective C method still can be invoked when object was released?
Class definition:
#import "MyClass.h"
@implementation MyClass
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)print
{
NSLog(@"Hello World");
}
@end
And main file:
MyClass * m = [[MyClass alloc]init];
[m print];
[m re开发者_运维百科lease];
[m print];
Result:
Hello World
Hello World
Why the 2nd method still invoked when object is released?
Releasing an object simply marks the memory it used as being available to be reused for other purposes. It doesn't overwrite it with zeroes or anything like that. In your example, you haven't created any new objects, so nothing has had a chance to reuse the memory formerly known as "m".
This why it's a common pattern to release an object and assign nil to the pointer, to prevent accidental re-use of an invalid object:
[m release]
m = nil;
That's because the memory for that object still is in place and hasn't been overwritten with garbage yet. Also, the method in question doesn't rely on any other (released) instance variable. In short: it's just pure chance that it worked.
Try setting the environment variable NSZombieEnabled and running that again to see that you really just had "luck".
Accessing freed memory is undefined behavior. When you're invoking undefined behavior, anything can happen. This falls under the heading of "anything," so it's a reasonable thing to have happen — so is accessing the wrong object or just crashing, which are also likely outcomes.
精彩评论