What are alternatives to “delegates” for passing data between controllers?

前端 未结 6 1621
清酒与你
清酒与你 2020-12-29 00:26

Are there alternatives to \"delegates\" to pass back data from one controller to another?

Just seems like a lot of work implementing a delegate just to pass back the

6条回答
  •  无人及你
    2020-12-29 01:27

    You could use many ways:

    1. Calling a method of the super controller, needs casting maybe
    2. Notifications
    3. Simple Key-Value-Observing
    4. Core Data

    Example for for 1.

    interface of your MainViewController: add a public method for the data to be passed

    - (void)newDataArrivedWithString:(NSString *)aString;
    

    MainViewController showing ChildController

    - (void)showChildController
    {
        ChildController *childController = [[ChildController alloc] init];
        childController.mainViewController = self;
    
        [self presentModalViewController:childController animated:YES];
    
        [childController release];
    }
    

    Child Controller header / interface: add a property for the mainViewController

    @class MainViewController;
    
    @interface ChildController : UIViewController {
        MainViewController *mainViewController;   
    }
    
    @property (nonatomic, retain) MainViewController *mainViewController;
    

    Child Controller passing data to the MainViewController

    - (void)passDataToMainViewController
    {
        NSString * someDataToPass = @"foo!";
        [self.mainViewController newDataArrivedWithString:someDataToPass];
    }
    

提交回复
热议问题