What exactly are protocols and delegates and how are they used in IOS?

后端 未结 3 713
野的像风
野的像风 2020-12-05 03:09

I\'m really confused about the concept of delegates and protocols. Are they equivalent of interfaces and adapter classes in Java? How do they work? None of the resources I\

3条回答
  •  余生分开走
    2020-12-05 03:43

    In it's simplest form a delegate is an object which receives messages from another object. And you do it all the time.

    So say you had car object with an engine.

    @interface car : NSObject
    
    @property (nonatomic) id engine;
    
    @end
    

    So could forward a start message to the engine.

    [_engine start];
    

    The engine is acting as a delegate, you're just passing it a message.

    Protocols make it more formal, and Xcode will check that you are conforming to the required or optional methods.

    @property (nonatomic) id  engine;
    

    says that the engine object MUST contain the function start because in the the protocol definition it asked for it.

    @protocol engineDelegate 
     - (void) start;
    @optional
     - (double) fuelLevel;
    @end
    

    Why are delegates and protocols so cool? Well because the engine could be any number of different engines which you could use at runtime, it could be a jet engine, a combustion engine, a phasing modulating engine it doesn't matter, as long as it conforms to the protocol. And you tell Xcode that it does conform by adding the delegate to the class interface.

    @interface timeWarpDrive : NSObject 
    

提交回复
热议问题