我在Objective-C中編寫一個方法使對象爲零時遇到了一些麻煩。下面是一些例子:Objective-C方法使對象無效
@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;
}
顯然,當我設置的測試對象爲nil,然後調用它的一些方法,什麼都不會發生,但如果我不是調用它直接設置爲nil,nillify,displayA法正常工作,像測試對象仍然存在。有沒有一種解決方法讓nillify方法正常工作?
非常感謝您的幫助!