How do I create delegates in Objective-C?

后端 未结 19 2519
一整个雨季
一整个雨季 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

    Swift version

    A delegate is just a class that does some work for another class. Read the following code for a somewhat silly (but hopefully enlightening) Playground example that shows how this is done in Swift.

    // A protocol is just a list of methods (and/or properties) that must
    // be used by any class that adopts the protocol.
    protocol OlderSiblingDelegate: class {
        // This protocol only defines one required method
        func getYourNiceOlderSiblingAGlassOfWater() -> String
    }
    
    class BossyBigBrother {
        
        // The delegate is the BossyBigBrother's slave. This position can 
        // be assigned later to whoever is available (and conforms to the 
        // protocol).
        weak var delegate: OlderSiblingDelegate?
        
        func tellSomebodyToGetMeSomeWater() -> String? {
            // The delegate is optional because there might not be anyone
            // nearby to boss around.
            return delegate?.getYourNiceOlderSiblingAGlassOfWater()
        }
    }
    
    // PoorLittleSister conforms to the OlderSiblingDelegate protocol
    class PoorLittleSister: OlderSiblingDelegate {
    
        // This method is repquired by the protocol, but the protocol said
        // nothing about how it needs to be implemented.
        func getYourNiceOlderSiblingAGlassOfWater() -> String {
            return "Go get it yourself!"
        }
        
    }
    
    // initialize the classes
    let bigBro = BossyBigBrother()
    let lilSis = PoorLittleSister()
    
    // Set the delegate 
    // bigBro could boss around anyone who conforms to the 
    // OlderSiblingDelegate protocol, but since lilSis is here, 
    // she is the unlucky choice.
    bigBro.delegate = lilSis
    
    // Because the delegate is set, there is a class to do bigBro's work for him.
    // bigBro tells lilSis to get him some water.
    if let replyFromLilSis = bigBro.tellSomebodyToGetMeSomeWater() {
        print(replyFromLilSis) // "Go get it yourself!"
    }
    

    In actual practice, delegates are often used in the following situations

    1. When a class needs to communicate some information to another class
    2. When a class wants to allow another class to customize it

    The classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.

    I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.

    • What is Delegation? – A Swift Developer’s Guide
    • How Delegation Works – A Swift Developer’s Guide

提交回复
热议问题