Search code examples
objective-cdelegatesios4modalviewcontrollerdelegation

Delegation and Modal View Controllers


According to the View Controller Programming Guide, delegation is the preferred method to dismiss a modal view.

Following Apple's own Recipe example, i have implemented the following, but keep getting warnings that the addNameController:didAddName method is not found...

NameDelegate.h
    @protocol NameDelegate
    - (void)addNameController:(AddName *)addNameController didAddName:(NSString *)name;
    @end

AddName.h
    @interface AddName : UIViewController {
        UITextField *nameField;
        id delegate;
    }
    - (IBAction)doneAction;
    - (id)delegate;
    - (void)setDelegate:(id)newDelegate;
    @property (nonatomic, retain) IBOutlet UITextField *nameField;
    @end

AddName.m
    - (IBAction)doneAction {
        [delegate addNameController:self didAddName:[nameField text]];
    }

    - (id)delegate {
        return delegate;
    }

    - (void)setDelegate:(id)newDelegate {
        delegate = newDelegate;
    }

ItemViewController.h
    #import "NameDelegate.h"
    @interface ItemViewController : UITableViewController <NameDelegate>{
    }
    @end

ItemViewController.m
    - (void)addItem:(id)sender {

        AddName *addName = [[AddName alloc] init];
        addName.delegate = self;
        [self presentModalViewController:addName animated:YES];
    }

    - (void)addNameController:(AddName *)addNameController didAddName:(NSString *)name {
        //Do other checks before dismiss... 
        [self dismissModalViewControllerAnimated:YES];
    }



I think all the required elements are there and in the right place?

Thanks


Solution

  • You haven't specified that the delegate property of AddName has to conform to the NameDelegate protocol.

    Use this code in AddName.h:

    #import "NameDelegate.h"
    
    @interface AddName : UIViewController {
        UITextField *nameField;
        id <NameDelegate> delegate;
    }
    
    @property(nonatomic, retain) IBOutlet UITextField *nameField;
    @property(nonatomic, assign) id <NameDelegate> delegate;
    
    - (IBAction)doneAction;
    
    @end