i have some trouble writing a method in Objective-C to make an object nil. Here is some example :
@interface testA : NSObject
{
NSString *a;
}
@property (nonatomic, retain) NSString *a;
+(testA*)initWithA:(NSString *)aString;
-(void)displayA;
-(void)nillify;
@end
@implementation testA
@synthesize a;
+(testA*)initWithA:(NSString *)aString{
testA *tst=[[testA alloc] init];
tst.a=aString;
return [tst autorelease];
}
-(void)displayA{
NSLog(@"%@",self.a);
}
-(void)nillify{
self=nil;
}
- (void)dealloc {
[a release];
[super dealloc];
}
@end
int main(int argc, char **argv){
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
testA *test=[testA initWithA:@"some test"];
[test displayA];
test=nil;
//[test nillify];
NSLog(@"after setting to nil");
[test displayA];
[pool release];
return 0;
}
Apparently , when I set test object to nil and then call some method on it nothing happens , but if i call nillify instead of directly setting it to nil , displayA method works normally like test object is still there. Is there a workaround for nillify method to function properly ?
Your help is much appreciated !
You can’t actually do something like this, because setting ‘self’ to nil only has any effect within the scope of that method (in your case, ‘nilify’). You don’t have any actual way to effect the values of pointers located on other parts of the stack or in random places in the heap, for example.
Basically any code that holds a reference to some object is responsible for maintaining and clearing those references itself. If you have some use case where random sections of code may need references to “live” objects of some kind, but where you’d want those object references to go away in response to some external event (maybe a user tracking system or something), you could do something with notifications, but the various modules tracking those “live” objects would still be responsible for listening for notifications and cleaning up references when they received them.
The ‘nilify’ thing, however, can’t possibly work.