Objective-C - pointer not nil after destroying the object
I'm playing a little on my linux with Objective-C. Actually I'm trying to learn it, and while working on this quest, I got stuck.
Here is the code:
#import <stdio.h>
#import <Foundation/NSObject.h>
开发者_高级运维int main(void) {
NSObject *a = [[NSObject alloc] init];
printf("Class retain count: %i\n", [a retainCount]);
printf("Is pointer nil: %i\n\n", (a==nil));
[a retain];
printf("Class retain count: %i\n", [a retainCount]);
printf("Is pointer nil: %i\n\n", (a==nil));
[a release];
printf("Class retain count: %i\n", [a retainCount]);
printf("Is pointer nil: %i\n\n", (a==nil));
[a release];
//printf("Class retain count: %i\n", [a retainCount]);
printf("Is pointer nil: %i\n", (a==nil));
return 0;
}
And this is the output:
Class retain count: 1
Is pointer nil: 0
Class retain count: 2
Is pointer nil: 0
Class retain count: 1
Is pointer nil: 0
Is pointer nil: 0
I've commented out last printf because it crashes the program (I get "Segmentation fault obj/test" 'cause a isn't set to nil ...). So what am I doing wrong ? Why isn't pointer set to nil ? It just keeps it's old value (before object is deleted) ...
releasing the object will not set it to nil. release
will release the object that is pointed by your variable (in this case a
) however you variable still pointing to the same object memory address unless you do assign another address like:
a = otherAddress;
usually you will do:
a = nil; //or
a = [[NSObject alloc] init]; //or
a = [MyObject objectWithSomething:smthg];
So, if you plan to reuse a
after its deallocated then set it to nil after you finished. To avoid "Segmentation fault" errors if by any chance you attempt to use a
and it is pointing to a deallocated object.
Why isn't pointer set to nil ?
Because pointers to Objective-C objects are just pointers. When you free
memory in plain C, you wouldn't expect your pointers to be set to NULL.
A pointer doesn't become nil
unless you assign nil
to it. That the pointer is invalid does not mean that it will be nil
. You have to consider a pointer just like any arbitrary integer: if you set it to some number, it will continue having that value until you set it otherwise.
That's why you can't use obj == nil
to check whether an object is still valid.
You will have to explicitly set the variable
nil
after releasing it.
[a release];
//This below line say : i don't have need to use the variable anymore.
a = nil ;
if you don't have any use of a variable then first release
and set that with nil
value. (Setting nil
is necessary).
精彩评论