Delegates Vs. Notifications in iPhoneOS

前端 未结 7 1881
既然无缘
既然无缘 2020-12-04 06:23

I am trying to call a method in my root view controller from a child view controller such that when I change my options they will automatically update the root view, which w

7条回答
  •  抹茶落季
    2020-12-04 07:00

    Delegates are a little hard to get used to, but I think it's the best practice and, like Apple, they just work.

    I always use the formal protocol declaration. It's a bit more logical in my mind, and it's very clear in the code. I suggest using a UIView to change your options instead of a controller. I always use one main controller and have a lot of subclassed UIViews that the one controller can control. (However, you can modify the following code for a controller, if you really need a controller instead of a normal view.) In the header file of the child view, make it look like this:

    // ChildView.h
    #import 
    
    @protocol ChildViewDelegate; // tells the compiler that there will be a protocol definition later
    
    @interface ChildViewController : UIView {
        id  delegate;
        // more stuff
    }
    
    // properties and class/instance methods
    
    @end
    
    @protocol ChildViewDelegate // this is the formal definition
    
    - (void)childView:(ChildView *)c willDismissWithButtonIndex:(NSInteger)i; // change the part after (ChildView *)c to reflect the chosen options
    
    @end
    

    The method between @protocol and the second @end can be called somewhere in the implementation of the ChildView, and then your root view controller can be the delegate that receives the 'notification.'

    The .m file should be like this:

    // ChildView.m
    #import "ChildView.h"
    
    @implementation ChildView
    
    - (id)initWithDelegate:(id)del { // make this whatever you want
        if (self = [super initWithFrame:CGRect(0, 0, 50, 50)]) { // if frame is a parameter for the init method, you can make that here, your choice
            delegate = del; // this defines what class listens to the 'notification'
        }
        return self;
    }
    
    // other methods
    
    // example: a method that will remove the subview
    
    - (void)dismiss {
        // tell the delegate (listener) that you're about to dismiss this view
        [delegate childView:self willDismissWithButtonIndex:3];
        [self removeFromSuperView];
    }
    
    @end
    

    Then the root view controller's .h file would include the following code:

    // RootViewController.h
    #import "ChildView.h"
    
    @interface RootViewController : UIViewController  {
        // stuff
    }
    
    // stuff
    
    @end
    

    And the implementation file will implement the method defined in the protocol in ChildView.h, because it will run when the ChildView calls for it to be run. In that method, put the stuff that happens when you'd get the notification.

提交回复
热议问题