我有下一个代码,非常简单:
//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;
}
基本上,当从一个按钮启动代码时,如果 UIViewController 不存在,则创建一个并显示它(它旨在显示在一个更大的主桌面 View 上,这是 SecondViewController View )。如果它已经打开,请将其关闭并删除以释放资源。
现在,contentRvController 是 ContentView 的一个实例,一个自定义的 UIViewController。它有它自己的关闭 UIButton IBAction 是这样的:
//ContentView.m
- (IBAction) closeView {
self.view.hidden = YES;
[self release];
self = nil;
}
现在,当从 SecondViewController 触发时,释放 contentRvController 工作正常(或者在我看来是这样), View 出现和消失。但是,当点击 ContentView 关闭按钮时,它也会关闭 View ,但是当再次尝试打开它时,
if(contentRvController==nil)
返回 FALSE
,所以我必须点击两次按钮才能再次显示 ContentView。在我看来
self = nil;
作品不同于 contentRvController = nil;
虽然它应该都指向同一个地方,我迷失了这个。任何的想法?来自墨西哥的欢呼
最佳答案
它们的工作方式相同,但它们并没有像你认为的那样做。 =
不影响对象;它影响指向对象的变量。将一个变量设置为 nil 不会改变程序中任何其他变量的值。相似地:
int a = 5;
int b = a;
b = 6;
printf("A is %d and B is %d\n", a, b);
这将打印“A is 5 and B is 6”——因为将 B 设置为新值不会改变 A 的值。
关于Objective-C:self = nil 不会将实例设置为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6767916/