How do I create delegates in Objective-C?

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

    To create your own delegate, first you need to create a protocol and declare the necessary methods, without implementing. And then implement this protocol into your header class where you want to implement the delegate or delegate methods.

    A protocol must be declared as below:

    @protocol ServiceResponceDelegate 
    
    - (void) serviceDidFailWithRequestType:(NSString*)error;
    - (void) serviceDidFinishedSucessfully:(NSString*)success;
    
    @end
    

    This is the service class where some task should be done. It shows how to define delegate and how to set the delegate. In the implementation class after the task is completed the delegate's the methods are called.

    @interface ServiceClass : NSObject
    {
    id  _delegate;
    }
    
    - (void) setDelegate:(id)delegate;
    - (void) someTask;
    
    @end
    
    @implementation ServiceClass
    
    - (void) setDelegate:(id)delegate
    {
    _delegate = delegate;
    }
    
    - (void) someTask
    {
    /*
    
       perform task
    
    */
    if (!success)
    {
    [_delegate serviceDidFailWithRequestType:@”task failed”];
    }
    else
    {
    [_delegate serviceDidFinishedSucessfully:@”task success”];
    }
    }
    @end
    

    This is the main view class from where the service class is called by setting the delegate to itself. And also the protocol is implemented in the header class.

    @interface viewController: UIViewController 
    {
    ServiceClass* _service;
    }
    
    - (void) go;
    
    @end
    
    @implementation viewController
    
    //
    //some methods
    //
    
    - (void) go
    {
    _service = [[ServiceClass alloc] init];
    [_service setDelegate:self];
    [_service someTask];
    }
    

    That's it, and by implementing delegate methods in this class, control will come back once the operation/task is done.

提交回复
热议问题