Monday 9 February 2009

Delegates

Objects communication is generally thought of as one way. Object A will create Object B. Then Object A can talk to Object B by calling its methods. Delegates are a way the Object B can talk back to Object A. 
This is useful in asynchronous or event driven situations. For example, Object A will tell Object B to go off and do something. Object A will then get on with its life without waiting for B to finish. When Object B is finished, it will call a delegate which will tell Object A that it is finished.

Heres how it works in Objective C.

Object B will need to keep a reference to Object A. In Object B's header wack in the following :

@interface ObjectB : NSObject 

{

    id delegate;

}


- (id)delegate;

- (void)setDelegate:(id)newDelegate;



Then chuck this in the implementation.

- (id)delegate 

{

    return delegate;

}


- (void)setDelegate:(id)newDelegate 

{

    delegate = newDelegate;

}


These are the getter and setter functions that Object A call to say it is interested in hearing from Object B. It would do something like :


    objB.delegate = self;


We need to define the function that will be called when Object B wants to talk to Object A. So back to the header file of Object B. Chuck this at the end :

@interface NSObject (ShareDelegate)

    - (void)finishedLoading:(id)sender;

@end

  
This is defining a function that will take one parameter, an id to Object B. You can have whatever parameters you want... Then when Object B wants to call the function it does this :

    if ( [delegate respondsToSelector:@selector(finishedLoading:)] ) 

    {

        [ delegate finishedLoading:self];

    }


Then all Object A has to do is define a function as normal like :

    - (void)finishedLoading:(id)sender;

    {

        self.label.text = @"done";

    }


Yippeee. Quite simple really...

No comments:

Post a Comment