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.
releasewill release the object that is pointed by your variable (in this casea) however you variable still pointing to the same object memory address unless you do assign another address like:usually you will do:
So, if you plan to reuse
aafter its deallocated then set it to nil after you finished. To avoid “Segmentation fault” errors if by any chance you attempt to useaand it is pointing to a deallocated object.