Search code examples
objective-csubviewibaction

Objective C: open and close a subview


This is my code with two IBAction for open and close a subview in two different classes

- (IBAction) showListClient:(id) sender {

if( list == nil){

    list = [[ListClient alloc] initWithNibName:@"ListClient" bundle:nil];
    [list setDelegate:self];
    [self.view addSubview:list.view];
}

}

and for close

-(IBAction)closeListClient {
[self.view removeFromSuperview];
}

now it's ok for the first time, but if I want use more time my list I must write in closeListClient

list = nil;
[list release];

now my problem is this "list" is declared only in the class ListClient as

ListClient *list;

and when I write list in CloseListClient is an error...what can I do?


Solution

  • In ListCLient.h define a protocol for its delegate:

    @protocol ListClientDelegate<NSObject>
    @optional
    - (void)listClientDidClose:(ListClient *)listClient;
    @end
    

    and modify the property definition for delegate:

    @property (nonatomic, assign) id<ListClientDelegate> delegate;
    

    Then send a message to the delegate when the closeListClient action is called (in ListClient.m):

    -(IBAction)closeListClient {
        [self.view removeFromSuperview];
        [self.delegate listClientDidClose:self]
    }
    

    Then finally in SomeController.m implement the delegate method:

    -(void)listClientDidClose:(ListClient *)listClient {
        [list release];
        list = nil;
    }
    

    I hope that solves your proplem.