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

前端 未结 6 1623
清酒与你
清酒与你 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:14

    Delegates aren't a lot of work, aren't a lot of code, and are commonly the most appropriate solution. In my opinion they're neither difficult nor messy.

    Five lines of code in the child's interface. Before @interface:

    @protocol MyUsefulDelegate 
    - (void)infoReturned:(id)objectReturned;
    @end
    

    Inside @interface:

    id  muDelegate;
    

    After @inteface's @end:

    @property (assign) id  muDelegate;
    

    One line of code in the child's implementation:

    [[self muDelegate] infoReturned:yourReturnObject];
    

    One addition to an existing line of code in the parent's interface:

    @interface YourParentViewController : UIViewController 
    

    Three lines of code in the parent's implementation. Somewhere before you call the child:

    [childVC setMuDelegate:self];
    

    Anywhere in the implementation:

    - (void)infoReturned:(id)objectReturned {
        // Do something with the returned value here
    }
    

    A total of nine lines of code, one of which is merely an addition to an existing line of code and one of which is a closing curly brace.

    It's not as simple as a returning a value from a local method, say, but once you're used to the pattern it's super straightforward, and it has the power of allowing you do do all kinds of more complex stuff.

提交回复
热议问题