objective C: problem with open a second time a subview
I have this code to open a subview
- (IBAction) showList:(id) sender {
if( list == nil){
list = [[ListClient alloc] initWithNibName:@"ListClient" bundle:nil];
[list setDelegate:self];
[self.view addSubview:list.view];
}
}
and this code to close thi开发者_JAVA技巧s subview
-(IBAction) closeListClient {
[self.view removeFromSuperview];
}
it's ok for the first time, but at second time when i want to open the subview, it don't work, why?
Because your list
is not nil
so it doesn't go inside if (list == nil)
.
Change it to if (list.superview == nil)
.
It's because of the if
statement. Change it to:
if ( list == nil ) {
list = [[ListClient alloc] initWithNibName:@"ListClient" bundle:nil];
[list setDelegate:self];
}
[self.view addSubview:list.view];
And it will work.
PS. To fix the memory management of this, add a retained property list
to the class so you can say
self.list = [[[ListClient alloc] initWithNibName:@"ListClient" bundle:nil] autorelease];
And you can say self.list = nil;
to release the object when you're done with it. (eg while dismissing or in your dealloc
method)
-(IBAction) closeListClient{
[self.view removeFromSuperview];
if ( list != nil ) {
[list release];
list=nil;
}}
精彩评论