How do I create delegates in Objective-C?

后端 未结 19 2573
一整个雨季
一整个雨季 2020-11-21 04:48

I know how delegates work, and I know how I can use them.

But how do I create them?

19条回答
  •  广开言路
    2020-11-21 05:21

    Let's start with an example , if we buy a product online ,it goes through process like shipping/delivery handled by different teams.So if shipping gets completed ,shipping team should notify delivery team & it should be one to one communication as broadcasting this information would be overhead for other people / vendor might want to pass this information only to required people.

    So if we think in terms of our app, an event can be an online order & different teams can be like multiple views.

    Here is code consider ShippingView as Shipping team & DeliveryView as delivery team :

    //Declare the protocol with functions having info which needs to be communicated
    protocol ShippingDelegate : class {
        func productShipped(productID : String)
    }
    //shippingView which shows shipping status of products
    class ShippingView : UIView
    {
    
        weak var delegate:ShippingDelegate?
        var productID : String
    
        @IBAction func checkShippingStatus(sender: UIButton)
        {
            // if product is shipped
            delegate?.productShipped(productID: productID)
        }
    }
    //Delivery view which shows delivery status & tracking info
    class DeliveryView: UIView,ShippingDelegate
    {
        func productShipped(productID : String)
        {
            // update status on view & perform delivery
        }
    }
    
    //Main page on app which has both views & shows updated info on product whole status
    class ProductViewController : UIViewController
    {
        var shippingView : ShippingView
        var deliveryView : DeliveryView
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // as we want to update shipping info on delivery view, so assign delegate to delivery object
            // whenever shipping status gets updated it will call productShipped method in DeliveryView & update UI.
            shippingView.delegate = deliveryView
            //
        }
    }
    

提交回复
热议问题