Reputation: 21808
Why this piece of code works:
NSNumber *a = [[NSNumber alloc] initWithInt:5];
[a release];
NSLog(@"%i", [a intValue]);// it shows 5. why???
The message intValue
is sent to the deallocated object. its reference count must be 0. What's going on?
Upvotes: 2
Views: 88
Reputation: 771
I think that NSNumber has a special implementation, just like NSString.
[NSNumber alloc] does not actually allocate memory, but rather returns a generic pointer. The allocation would be handled by one of the init methods, but here again initWithInt:5 is such a common situation, that instead of creating a new object a pointer to a default one is returned. And this one cannot be released anyway.
// do it once
NSNumber* five1 = [NSNumber alloc];
NSLog(@"%p", five1);
five1 = [five1 initWithInt:5];
NSLog(@"%p", five1);
// and once more
NSNumber* five2 = [NSNumber alloc];
NSLog(@"%p", five2);
five2 = [five2 initWithInt:5];
NSLog(@"%p", five2);
In fact, there should be no problem with sending a release message more than once:
[five1 release];
[five1 release];
[five1 release];
Upvotes: 2
Reputation: 2122
Releasing the pointer just tells the OS memory manager that the memory is no longer in use - the block of memory that the object sat in will not actually be changed.
However, since this is now "dead" memory, it's likely that a later allocation will re-use that block of memory.
If you experiment by putting additional allocations in between your release and the log value, you should be able to see this happening.
Upvotes: 2
Reputation: 127
I guess it won't work if you set 'a' to nil, but as long as it points to some place in the heap and there is a 5 integer there, you get that 5. But if you do something between the release and the NSLog you may get a different result (any kind of trash).
Upvotes: 0