Objective-C:self = nil不会将实例设置为空值
我有下一个代码,非常简单:
//SecondViewController.m if(contentRvController==nil){ contentRvController = [[ContentView alloc] initWithNibName:@"ContentView" bundle:nil]; //ContentView is a custom UIViewController .... [self.view addSubview:contentRvController.view]; } else{ contentRvController.view.hide = YES; [contentRvController release]; contentRvController = nil; }
基本上,当从一个button启动代码时,如果UIViewController不存在,创build一个并显示它(这是为了显示在一个主要的更大的桌面视图,这是SecondViewController视图)。 如果它已经打开,closures它并将其删除以释放资源。
现在,contentRvController是ContentView的一个实例,一个自定义的UIViewController。 它有它自己的密切的UIButton其IBAction是这样的:
//ContentView.m - (IBAction) closeView { self.view.hidden = YES; [self release]; self = nil; }
现在,当从SecondViewController触发时,释放contentRvController正常工作(或者对我来说),视图出现并消失。 但是,当点击ContentViewclosuresbutton时,它也会closures视图,但是当试图再次打开它时, if(contentRvController==nil)
将返回FALSE
,所以我必须点击两次button才能再次显示ContentView。
在我看来, self = nil;
工作不同于contentRvController = nil;
虽然它被认为是指向同一个地方,并与我失去了这一点。
任何想法? 来自墨西哥的欢呼声
他们以同样的方式工作,但他们没有做你认为他们做的事情。 =
不影响对象; 它会影响指向该对象的variables。 设置一个variables指向nil不会改变程序中任何其他variables的值。 同理:
int a = 5; int b = a; b = 6; printf("A is %d and B is %d\n", a, b);
这将打印“A是5和B是6” – 因为将B设置为新值不会改变A的值。
没有对象应该释放自己。 处理对象的正常方法是在你释放任何ivars的地方实现-dealloc,然后像这样调用[super dealloc]。
- (void) dealloc; { [someIvar release]; [someOtherIvar release]; [super dealloc]; }
你一定要退后一步,阅读Objective-C中的对象生命周期,否则一个bug的世界等待着你。 苹果的视图控制器编程指南的iOS是不长的。 只是谷歌的标题。 省去很多麻烦