I am very new to Objective-C and was reading through memory management. I was trying to play around a bit with the NSAutoreleasePool but somehow it wont release my object.
I have a class with a setter and getter which basically sets a NSString *name. After releasing the pool I tried to NSLog the object and it still works but I guess it should not?
@interface TestClass : NSObject
{
NSString *name;
}
- (void) setName: (NSString *) string;
- (NSString *) name;
@end
@implementation TestClass
- (void) setName: (NSString *) string
{
name = string;
}
- (NSString *) name
{
return name;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
TestClass *var = [[TestClass alloc] init];
[var setName:@"Chris"];
[var autorelease];
[pool release];
// This should not be possible?
NSLog(@"%@",[var name]);
return 0;
}
Your code has several problems. First, you do neither
copynorretainthe string stored into thenameinstance variable. So, if the string is released by whoever stored it into the property, you are left with a dangling reference. You should door use properties right from the start.
Also, if you keep object references in instance variables, you should provide a proper definition of the
deallocmethod:Finally, just because an object has been deallocated, does not mean, that the memory of the former instance is invalidated. Your original program is most likely calling a method on a dangling reference (
var), which happens to work by sheer luck here. (In particular, to (auto)releasedoes not automatically set the reference tonil).