Tuesday, 12 February 2013

Cocoa design patterns: Target-Action and Observer

It's not just delegates.   

Along with delegates, you can use other ways to control interaction between objects, two important methods along with delegates are Target-action and Observer patterns



Targer-Action

we will use UIControl as the best example of Target-action technique to interact with object. 

when you have UIControl (say Button). this button has events based on user taps and touch gestures.

say we want to handle the event "tap the button", there must be someone listen to you when you tap this button and this one is your "target". so the next step is to define the event "Target" and the "action" it will take. 

you can make a command like that 
[Button addTarget:"object" action:"some method" forEvent:"tap on the button"];

in the previous line, button will call a specific method in the target object when some one tap this button.

another example of target/action technique is NSTimer class.when you want to call a method after predefined duration you would use the same code as the button example except for defining the event, here is the code snippet

[NSTimer addSheduleAfterTime:"time in seconds" target:"object" selector:"some method"];

you can see that selector here is the action performed at the end of the time.

The code above is not exact, in using selectors you must provide name of existing function without parameter names or types. 

The observer

another method to control the interaction between objects, common way of this method is NSCenterNotification object, it act as a middle ware between one object "A", and other objects want to be notified about this object "A" states.

you can think of it like twitter, one peson has followers, and whenever this person say something about himself, all of his followers get notified. they may take actions like retweet, reply or others based on the user mood.

an objective C example is like 

one object send notifications to others 
[NSNotificationCenter defaultCenter] postNotificationOnMessage"somePostName"];

and to subscribe to this object you will add yourself as obsever "or in twitter world as follower" to receive states from this object like that 
[NSNotificationCenter defailtCenter]addObserver:"your object reference" performSelector:"action taken when notified" onMessage:"post message you want to subscribe"];

and every time the object update the notification center with his message, other observeres in turn will be notified and take actions according to their methods


so far we presented three methods of common objects interactions they are delegates, target-action and observer. in the coming post i will talk about our singleton design pattern "last post on design patterns", and how to make center controls of your data. 

Salam,
M.Aleem



No comments:

Post a Comment