问题
I've got the next code, pretty simple:
//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;
}
Basically, when the code is launched from a button, if the UIViewController does not exist, create one and display it (it is meant to be displayed on a main bigger desktop view, this is the SecondViewController view). If it is already opened, close it and remove it to free resources.
Now, contentRvController is an instance of ContentView, a custom UIViewController. It has it's own close UIButton which IBAction is this:
//ContentView.m
- (IBAction) closeView {
self.view.hidden = YES;
[self release];
self = nil;
}
Now, when triggered from SecondViewController, releasing contentRvController works properly (or so it seems to me), the view appears and disappears. But when the ContentView close button is tapped it also closes the view, but when trying to open it again the if(contentRvController==nil)
returns FALSE
, so I have to tap twice the button to execute in order to display again the ContentView.
It seems to me that self = nil;
works different than contentRvController = nil;
although it is supposed both points to the same place, and im lost with this.
¿Any idea? Cheers from México
回答1:
They work the same way, but they're not doing what you think they do. The =
does not affect the object; it affects the variable pointing to the object. Setting one variable to point to nil won't change the value of any other variables in your program. Similarly:
int a = 5;
int b = a;
b = 6;
printf("A is %d and B is %d\n", a, b);
This will print "A is 5 and B is 6" — because setting B to a new value doesn't change the value of A.
回答2:
No object should release itself. The normal way to dispose of an object is to implement -dealloc where you release any ivars, then call [super dealloc] like this.
- (void) dealloc; {
[someIvar release];
[someOtherIvar release];
[super dealloc];
}
You should definitely take a step back and read up on the object lifecycle in Objective-C, else a world of bugs await you. Apple's View Controller Programming Guide for iOS is not long at all. Just Google for that title. Save yourself a lot of trouble.
来源:https://stackoverflow.com/questions/6767916/objective-c-self-nil-doesnt-set-instance-to-null-value