Delegates in Objective-C [duplicate] - objective-c

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How does a delegate work in objective-C?
Hello Community,
I have been trying to understand the concept of delegates in Objective-C. I tried following up the documentation, however I am looking for some really easy example to get familiarized as of how to send messages between delegates and if I want to create a custom delegate, how may I go further with that?
Hope someone could make me better understand this concept.

The basic concept of delegates is to delegate important decisions or information to some other object instance.
In most frameworks you use subclassing and override methods in order to hook into the application flow. It works but the drawbacks are many, for example:
You can not change the decision maker without a complete new subclass.
Without multiple inheritance you can only make decisions for one object (yourself).
There are four reasons why an object might want to call upon a delegate, and each of these four uses a keyword in the delegate method name to signal this. It's a naming convention only, but you should follow the pattern if you want to be a good citizen.
Ask if something should happen. For example: gestureRecognizer:shouldReceiveTouch:
Before something unavoidable is going to happen. For example: applicationWillTerminate:.
After something has occured. For example: accelerometer:didAccelerate:
And to retrieve data, this is more a data source than a delegate, but the line between the two are fuzzy. The name do not contain a defined name, but should contain the named piece of data that is requested. For example: tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:
As a general rule the first argument to any delegate method should be the named object instance requesting delegation.

Check here:How do I create delegates in Objective-C?
Or: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW18

Related

xCode / Objective-C Anatomy Analogies - Help a Noob Get It

OK so I'm trying to get started with Xcode and I have some experience with OOP in general but mostly I'm used to scripting. Anyhoo, I'm trying to get a handle on some concepts in objective C and xcode and I'm having some problems putting everything together.
For starters, I'm having trouble understanding what delegates and protocols do. I think it would be useful if someone could explain this with a simple analogy of a postman, or a teacher, or a factory or something. I don't understand the difference between a method in a delegate and a regular class methods.
Say I have a Class Postman. Now postman has methods sortMail() and deleteMail(). What's an example of a delegate method. And if a delegate is used, where is the data returned? Inside the delegate? Do I have to instantiate the delegate and then read results from it or does the delegate kinda give the results back to the calling object? Where do protocols come in...
Simple examples please :) Baby steps.
Protocols and Delegates go together frequently. It helps to understand what a protocol is first.
Protocol
A protocol is a way of having a class promise to implement a standard set of methods.
Example: A certified electrician has a certain set of skills that all certified electricians will have. If you need someone to do something that a certified electrician is certified to do, then any certified electrician should be able to do it (in theory at least).
Delegate
Now a delegate is an object that has been given a responsibility to fulfill certain requirements. One object can be given the responsibility of fulfilling a need of another object.
Example: When building a house, the house needs to have wires run etc. This responsibility has been given to a certified electrician, and we know he can do it because he's certified (i.e. implements a certain protocol).
Putting it all together in a Cocoa context:
A UITableView needs cells supplied so it can display them. To supply the cells, a class will need to be created (or at least specified) which implements the UITableViewDataSource protocol. That guarantees that the class does the needed things to supply the UITableView with the needed cells.
So the UITableView delegates the responsibility of providing the cells to a certain class object which implements the protocol which guarantees that the object knows how to supply the needed cells.
Example
A delegate is an object that handles particular functionality for another object - as in "Object A delegates certain functionality to object B".
For instance, you may use an instance of Apple's class NSURLConnection to make a request for a web service, but Apple's code obviously won't know what to do with the data it downloads, so you provide a delegate object to handle that functionality. NSURLConnection then delegates that functionality to your object by passing it messages when it needs to do something like handle the data it downloads.
Another example is a table view. Apple have written a lot of code to display table views and handle interactions with them, but it doesn't know what data you want to display or what needs to be done with that data when somebody interacts with it. So you can provide delegate objects for these things. When a table view needs to know what data to display, it asks your delegate to fetch the data for it. When the user selects an item, it asks your delegate to handle it.
A protocol is simply a way of describing what messages the delegate is supposed to understand. There can be informal protocols, where it's just described in the documentation, and formal protocols, which are defined in a header file.

"Finding" an object instance of a known class?

My first post here (anywhere for that matter!), re. Cocoa/Obj-C (I'm NOT up to speed on either, please be patient!). I hope I haven't missed the answer already, I did try to find it.
I'm an old-school procedural dog (haven't done any programming since the mid 80's, so I probably just can't even learn new tricks), but OOP has my head spinning! My question is:
is there any means at all to
"discover/find/identify" an instance
of an object of a known class, given
that some OTHER unknown process
instantiated it?
eg. somthing that would accomplish this scenario:
(id) anObj = [someTarget getMostRecentInstanceOf:[aKnownClass class]];
for that matter, "getAnyInstance" or "getAllInstances" might do the trick too.
Background: I'm trying to write a plugin for a commercial application, so much of the heavy lifting is being done by the app, behind the scenes.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
I've spent untold hours and days going over Apples documentation, tutorials and lots of example/sample code on the web (including here at Stack Overflow), and come up empty. Seems that everything requires a known target object to work, and I just don't have one.
Since I may not be expressing my problem as clearly as needed, I've put up a web page, with diagram & working sample pages to illustrate:
http://www.nulltime.com/svtest/index.html
Any help or guidance will be appreciated! Thanks.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
If this is a publicly declared class with publicly declared instance methods (i.e., you have the header for the class and it has instance methods in it), there is probably a way in this application's API to get an instance of the class. Either you are meant to create one yourself, or the application has one (or more) and provides a way to get it (or them). Look at both the header for the class in question and the other headers.
I initially said “there must be a way…”, but I changed it, because there is an alternative reason why the header would have instance methods: The application developer does not intend those instance methods for plug-in use (and didn't mark them appropriately), or did not mean to include that header in the application/SDK (they included it by accident). You may want to ask the application developer for guidance.
If it is not a publicly declared class or its instance methods are not publicly declared, then the application does not support you working with instances of the class. Doing so is a breach of the API contract—not a legal contract, but the expectations that the application has of its plug-ins. If you breach the API contract, you will cause unexpected behavior, either now (not necessarily on your own machine/in your own tests) or in the future.
If the class's public declaration contains only class methods, then perhaps what you're after is not an instance at all—you're supposed to send those messages to the class itself.
This is not possible without having you register each instance in a dictionary as it is created. I.e., override some common factory method at a higher level which does this bookkeeping work. This will fall down when you use delegates that you may not control though, keep that in mind.
I do question the need to even do this at all, but I don't know your problem as well as I perhaps would need to, to recommend a different, more apt way of accomplishing the actual task at hand.
Just as a corollary to the above; I did look at the runtime to see if there was anything that I actually forgot about, but there is not. So my above statement with regards to you requiring to do that bookkeeping yourself, still holds I'm afraid.
Edit:
Based on your diagram (my apologies, just noticed the link after I posted this answer); I would suggest that if you control the classes that are being returned to you, just add a property to them. I.e., add a "name" property that you can set and keep unique. Then just pass the message to each instance, checking whether or not that object is the one you want. It's not particularly clever or anything like that, but it should work for your purposes.

Obj-C component-based game architecture and message forwarding

I've been trying to implement a simple component-based game object architecture using Objective-C, much along the lines of the article 'Evolve Your Hierarchy' by Mick West. To this end, I've successfully used a some ideas as outlined in the article 'Objective-C Message Forwarding' by Mike Ash, that is to say using the -(id)forwardingTargetForSelector: method.
The basic setup is I have a container GameObject class, that contains three instances of component classes as instance variables: GCPositioning, GCRigidBody, and GCRendering. The -(id)forwardingTargetForSelector: method returns whichever component will respond to the relevant selector, determined using the -(BOOL)respondsToSelector: method.
All this, in a way, works like a charm: I can call a method on the GameObject instance of which the implementation is found in one of the components, and it works. Of course, the problem is that the compiler gives 'may not respond to ...' warnings for each call. Now, my question is, how do I avoid this? And specifically regarding the fact that the point is that each instance of GameObject will have a different set of components? Maybe a way to register methods with the container objects, on a object per object basis? Such as, can I create some kind of -(void)registerMethodWithGameObject: method, and how would I do that?
Now, it may or may not be obvious that I'm fairly new to Cocoa and Objective-C, and just horsing around, basically, and this whole thing may be very alien here. Of course, though I would very much like to know of a solution to my specific issue, anyone who would care to explain a more elegant way of doing this would additionally be very welcome.
Much appreciated, -Bastiaan
I don't think that sending the container object all of its components' messages is what Mick West was suggesting--that doesn't help to remove the idea of a "monolithic game entity object".
The eventual goal is to have the components communicate directly with one another, with no container object at all. Until then, the container object acts as glue between old code that expects a single object for each game entity and the new component-to-component system.
That is, you shouldn't need to use message forwarding at all in the final product, so ignoring the warnings, or declaring variables as id for now to quiet them, isn't all that ugly. (The plan as laid out by the article is to eventually remove the very code that is causing your warnings!)
A simple way to have those warnings disappear would be to declare the instance variables of type id
That way the compiler assumes you know what you're doing regarding the type of the object and that the object will respond to whatever messages you send to it, or if it doesn't you don't care.
Override your GameObject's -respondsToSelector: method. Your implementation should in turn send a respondsToSelector: message to each of its instances, and return YES if any one of them returns YES.
You can use type of id - or you could invoke the methods using performSelector methods, or create an NSInvocation if the arguments are complex. This is all just a way of getting around compiler warnings, however. If your objects respond to several methods, then possibly declaring a protocol might help, although the same caveat applies.
Another option if I understand the problem correctly is to implement a protocol. This is link an interface in java and variables can be declared like this:
id anObjectRef
That way the compiler understands that the object referred to by anObjectRef conforms to the protocol.
There are also methods that can tell you if an particular object conforms to a specific protocol before you cast or assign it.

Abstract design / patterns question

I had a bunch of objects which were responsible for their own construction (get properties from network message, then build). By construction I mean setting frame sizes, colours, that sort of thing, not literal object construction.
The code got really bloated and messy when I started adding conditions to control the building algorithm, so I decided to separate the algorithm to into a "Builder" class, which essentially gets the properties of the object, works out what needs to be done and then applies the changes to the object.
The advantage to having the builder algorithm separate is that I can wrap/decorate it, or override it completely. The object itself doesn't need to worry about how it is built, it just creates a builder and 'decorates' the builder with extra the functionality that it needs to get the job done.
I am quite happy with this approach except for one thing... Because my Builder does not inherit from the object itself (object is large and I want run-time customisation), I have to expose a lot of internal properties of the object.
It's like employing a builder to rebuild your house. He isn't a house himself but he needs access to the internal details, he can't do anything by looking through the windows. I don't want to open my house up to everyone, just the builder.
I know objects are supposed to look after themselves, and in an ideal world my object (house) would build itself, but I am refactoring the build portion of this object only, and I need a way to apply building algorithms dynamically, and I hate opening up my objects with getters and setters just for the sake of the Builder.
I should mention I'm working in Obj-C++ so lack friend classes or internal classes. If the explanation was too abstract I'd be happy to clarify with something a little more concrete. Mostly just looking for ideas or advice about what to do in this kind of situation.
Cheers folks,
Sam
EDIT: is it a good approach to declare a
interface House(StuffTheBuilderNeedsAccessTo)
category inside Builder.h ? That way I suppose I could declare the properties the builder needs and put synthesizers inside House.mm. Nobody would have access to the properties unless they included the Builder header....
That's all I can think of!
I would suggest using Factory pattern to build the object.
You can search for "Factory" on SO and you'll a get a no. of questions related to it.
Also see the Builder pattern.
You might want to consider using a delegate. Add a delegate method (and a protocol for the supported methods) to your class. The objects of the Builder class can be used as delegates.
The delegate can implement methods like calculateFrameSize (which returns a frame size) etc. The returned value of the delegate can be stored as an ivar. This way the implementation details of your class remain hidden. You are just outsourcing part the logic.
There is in fact a design pattern called, suitable enough, Builder which does tries to solve the problem with creating different configurations for a certain class. Check that out. Maybe it can give you some ideas?
But the underlying problem is still there; the builder needs to have access to the properties of the object it is building.
I don't know Obj-C++, so I don't know if this is possible, but this sounds like a problem for Categories. Expose only the necessary methods to your house in the declaration of the house itself, create a category that contains all the private methods you want to keep hidden.
What about the other way around, using multiple inheritance, so your class is also a Builder? That would mean that the bulk of the algorithms could be in the base class, and be extended to fit the neads of you specific House. It is not very beautiful, but it should let you abstract most of the functionality.

Where do I use delegates? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.
As stated in "Learning C# 3.0: Master the fundamentals of C# 3.0"
General Scenario: When a head of state dies, the President of the United States typically does not have time to attend the funeral
personally. Instead, he dispatches a delegate. Often this delegate is
the Vice President, but sometimes the VP is unavailable and the
President must send someone else, such as the Secretary of State or
even the First Lady. He does not want to “hardwire” his delegated
authority to a single person; he might delegate this responsibility to
anyone who is able to execute the correct international protocol.
The President defines in advance what responsibility will be delegated
(attend the funeral), what parameters will be passed (condolences,
kind words), and what value he hopes to get back (good will). He then
assigns a particular person to that delegated responsibility at
“runtime” as the course of his presidency progresses.
In programming Scenario: You are often faced with situations where you need to execute a particular action, but you don’t know in
advance which method, or even which object, you’ll want to call upon
to execute it.
For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particular
object, you will connect the button to a delegate and then resolve
that delegate to a particular method when the program executes.
A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines.
Based on this statement, a delegate is a function pointer and it defines what that function looks like.
A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.
One common use of delegates for generic Lists are via Action delegates (or its anonymous equivalent) to create a one-line foreach operation:
myList.Foreach( i => i.DoSomething());
I also find the Predicate delegate quite useful in searching or pruning a List:
myList.FindAll( i => i.Name == "Bob");
myList.RemoveAll( i => i.Name == "Bob");
I know you said no code required, but I find it easier to express its usefulness via code. :)
Binding Events to Event Handlers is usually your first introduction to delegates...You might not even know you were using them because the delegate is wrapped up in the EventHandler class.
I had the same question as you and went to this site for an answer.
Apparently, I didn't understood it better even though I skimmed through the examples on this thread.
I found a great use for delegates now that I read: http://www.c-sharpcorner.com/UploadFile/thiagu304/passdata05172006234318PM/passdata.aspx
This might seem more obvious for new users because Forms is much more complicated to pass values than ASP.NET websites with POST/GET (QueryString) ..
Basically you define a delegate which takes "TextBox text" as parameters.
// Form1
// Class Property Definition
public delegate void delPassData(TextBox text);
// Click Handler
private void btnSend_Click(object sender, System.EventArgs e)
{
Form2 frm= new Form2();
delPassData del=new delPassData(frm.funData);
del(this.textBox1);
frm.Show();
}
// SUMMARY: Define delegate, instantiate new Form2 class, assign funData() function to delegate, pass in your textBox to the delegate. Show the form.
// Form2
public void passData(TextBox txtForm1)
{
label1.Text = txtForm1.Text;
}
// SUMMARY: Simply take TextBox txtForm1 as parameters (as defined in your delegate) and assign label text to textBox's text.
I hope this enlightens some use on delegates :) ..
If you're interested in seeing how the Delegate pattern is used in real-world code, look no further than Cocoa on Mac OS X. Cocoa is Apple's preferred UI toolkit for programming under Mac OS X, and is coded in Objective C. It's designed so that each UI component is intended to be extended via delegation rather than subclassing or other means.
For more information, I recommend checking out what Apple has to say about delegates here.
I had a project which used win32 Python.
Due to various reasons, some modules used odbc.py to access the DB, and other modules - pyodbc.py.
There was a problem when a function needed to be used by both kinds of modules. It had an connection object passed to it as an argument, but then it had to know whether to use dbi.dbiDate or datetime to represent times.
This was because odbc.py expected, as values in SQL statements, dates as dbi.dbiDate whereas pyodbc.py expected datetime values.
One further complication was that the connection objects created by odbc.py and pyodbc.py did not allow one to set additional fields.
My solution was to wrap the connection objects returned by odbc.odbc(...) and pyodbc.pyodbc(...) by a delegate class, which contains the desired time representation function as the value of an extra field, and which delegates all other field requests to the original connection object.
A quick google search came up with this http://en.wikipedia.org/wiki/Delegation_pattern . Basically, anytime that you use an object that forwards it's calls to another object then you are delegating.