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

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.

Related

How to wrap class properties?

there is a conceptional question:
I want to have a wrapper class which forwarding all called selectors to a given object. How do I do this?
And here is why:
I have a library for synchronizing data with a service. And I use Core Data.
For the library I have to create classes of a specific protocol. But I can not use the same protocol for the Core Data subclasses.
My idea is to create a subclass of the specific protocol and forwarding the protocol calls to the Core Data Object.
But there are many subclasses and many properties per subclass and without changing the Core Data subclasses (project specific requirement!)
Is there a way to do this without overwriting every method?
Thanks for your time =)
Implement -forwardingTargetForSelector:. You can return another object to forward unknown messages to. If that is most of what your class will do, you may want to just subclass from NSProxy rather than NSObject. (NSProxy has the advantage that it doesn't implement all of the standard NSObject methods, so you can forward those as well.)
One common problem with this approach is that the compiler will complain that your class does not respond to the selectors you're sending it. The usual way to address this is by requiring that users of your object declare it as id. This can often be inconvenient as well, so this is a bit of a last resort if other approaches are not possible.
But usually the better approach is to make your class a subclass of the target and add the additional methods required for your protocol. Or you can add the additional methods to the Core Data class via a category.
The answer to your specific question is yes. Message Forwarding contains everything you need.
I think you might want to step back and evaluate other options. For example, can you add this functionality to a base class instead of a proxy class.

AFNetworking design pattern for wrapping REST requests/responses as objects

I am working on an IOS project that uses AFNetworking 2.0 for REST communication. I am interested to know if there is a good design pattern for wrapping requests/responses as individual classes. I want to create a base class, say AbstractHTTPRequest that has basic completion code (i.e. was the request successful, checks etc) that will be common to all AbstractHTTPRequest derived classes.
One of the derived classes will be say a Sign-up request (SignupHTTPRequest) that derives from AbstractHTTPRequest. Then I want to have a "client" classes with methods corresponding to each request, say:
#interface MyHTTPClient
(SignupHTTPRequest *) newSignupRequest...;
#end
I want to know if anyone else wrapped the NSURLSessionDataTask / NSURLRequest etc classes used by AFNetworking into a coherent set of classes like I want to do. It is important for me to encapsulate the whole thing (logic, data, etc) into a class, but so far most attempts have been completely messy and I am not happy with it. The messy bit has to do with the fact that most approaches imply two sets of completion blocks. One used by the generic class (AbstractHTTPRequest) for the AFNetworking completions, then another set for the code that uses the actual HTTPRequest. You end up with this nasty chain of completion blocks.
Any ideas?
R
[Ideas...]
1)Elegancy. So you want to tag certain "classes" of code to always call some default convenience methods? Here's the relationship I see:
In human terms I would "delegate" a task to always be done by person1 because his role is "defined" when working with "me."
Does creating a objective-c protocols for delegates help? I'm reminded of pretty Python decorators but can't quite translate it.
2)Did I read BTL's right that you were trying ...finally blocks to indiscriminately run the common-calls?

Standard delegate pattern seems at odds with delegate purpose

If I follow any of a number of examples available on the web, I see a common theme emerge with the delegate pattern:
myClass.delegate = self;
From what I read, delegation is supposed to uncouple behavior, but allow interaction between classes, however, only assigning a single delegate seems to be 100% at odds with this behavior.
I have a web dev background, and I am intimately familiar with pub/sub patterns, but what I'm trying to wrap my head around is why I would only allow a single delegate (self) to be able to act on whatever happens in myClass. That would seem to ruin the entire point of delegation.
Maybe I'm misunderstanding something, or maybe this is only the simplest form of delegation, but could someone please explain how statically assigning (in the classic sense) one class to another's delegate decouples behavior in any meaningful way.
Bonus: Perhaps a way to allow multiple classes to act on a delegation.
The delegate asserts additional control over the delegated class. The most simple example is windowShouldClose: method in the NSWindowDelegate protocol. The class delegate gets a chance to proactively override closing the window in NSWindow. If multiple delegates were allowed, multiple delegates could supply conflicting orders which would be an undesirable result.
Delegation allows you to customize behavior without subclassing. Because a class can implement many delegate protocols, it is a key part of the MVC programming model in Objective-C. Delegation allows you to create one class as a "Controller" of multiple other classes.
For acting reactively to what happens to the class, you use a pub/sub model of key value observing. For example, NSOperationQueue has an observable property operationCount to let you react to changes in the number of operations in the queue.
It decouples behavior in the sense that the delegator needn't know anything at all about the delegate other than that it (possibly) responds to a certain set of methods. This makes it so that classes that have delegate can be used in entirely different codebases/situation without changes. It's particularly applicable when writing Framework classes that will be used by someone else, which is one reason you see it so much in the system frameworks.
One of the major uses of delegation is to allow customization of an object's behavior without subclassing. Take for example the NSWindowDelegate method -windowWillResize:toSize:, where the delegate can return a different size than the suggested one to implement custom sizing behavior. How would this scenario be handled with multiple delegates each returning a different value?
Of course, sometimes delegate methods are merely meant to inform the delegate that some particular event has occurred. In these cases, it is indeed reasonable for multiple objects to want to be notified. This is provided for in Objective-C/Cocoa by notifications (NSNotification), and Key Value Observing (KVO). You'll find plenty of cases in Cocoa where a delegate method also has a corresponding notification posted in case objects other than the delegate want to know about it (e.g. windowWillClose:/NSWindowWillCloseNotification).

What are the key reasons for using #protocols in Objective C? [duplicate]

This question already has answers here:
What is a Protocol?
(2 answers)
Closed 10 years ago.
Why would I want to use a protocol rather than create a subclass and inherit the methods..?
Please explain it to me, i'm to confused about this topic, i'm not very pleased with the explanation in the book im reading.
Where do I use protocols instead of other ways to get the methods..? if I can subclass a class and get the methods why would i want to use a protocol where i need to define the methods?
Why would I want to use a protocol rather than create a subclass and
inherit the methods..?
Protocols make it possible for unrelated classes to all implement the same interface. Instances of each of those classes can then be used by a client of the protocol. For example, UITableViewDataSource is a protocol that provides an interface by which a table can ask for data from any object that implements the protocol. The table view doesn't care what the type of the object is so long as it implements the data source interface.
Imagine how unpleasant things would be if all table data sources had to inherit from a common class! Objective-C only provides single inheritance, so you'd effectively be constrained to using only a single kind of object for your data source. With protocols, though, a data source can be a view controller, a model object, or perhaps even a remote object.
To be more specific, protocols allow a form of polymorphism. That means that a single object can take several forms: e.g. view controller, table data source, table delegate, scroll view delegate. Because Objective-C is a single-inheritance language, you only get one of those interfaces via inheritance. The rest you implement yourself, but that often makes sense because you generally adopt a given protocol in order to customize some other object's behavior anyway.
Because subclassing and protocols are two different things. Subclassing extends a class with new functionality while inheriting all previous functionality of a specific class while a protocol, when applied to a class, simply adds functionality to it and doesn't inherit anything from it; what that class is usually doesn't matter.
Protocols are most frequently used for the delegate pattern in Objective-C whereby an object can send a message to another object without caring WHAT that object is (i.e. it's class).
Often times, a delegate is declared as:
#property(nonatomic, assign) id < MyObjectDelegate > delegate;
Notice that the class of the property is id -- in essence, you don't care if the object is a car or a turtle -- all you need to know is that it is an object (id) and that it contractually subscribes to the functions you need it to. So if your delegate is type turtle, you can call [delegate myStateChanged]; or, if your delegate is a car, you can call [delegate myStateChanged]. All you need to know is that, if you send a message to it, it will accept it.
I would look up and read about the use of Objective-C delegates as I think it will really help you understand protocols better and how it's different than subclassing. I don't know if you're familiar with other, object-oriented programming languages, but if so, protocols are most similar to Interfaces in other languages.
Protocols are useful because you can implement many protocols, instead you can only extend a single class.

how do i know when to use a datasource or delegate protocol when using a UI object in my project?

for example the UIPickerView, in the tutorial that i am learning i had to include the datasource and delegate protocols in my project for the pickerview to work. how would i know on other objects?
In general that is explained in the documentation of the individual object. For example http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIPickerView_Class/Reference/UIPickerView.html
In the Overview section it explains that, "the delegate must adopt the UIPickerViewDelegate protocol" and that, "the data source must adopt the UIPickerViewDataSource protocol"
From http://developer.apple.com/iphone/index.action just type the name of the object you are interested in into the search box and the documentation should explain everything needed to make it go.
To note, the UIPickerViewDelegate/Datasource are representative of the Delegate design pattern (see Cocoa Design Patterns) and are repeated throughout the Cocoa UI hierarchy as a method of modifying behavior of an object without having to subclass. It's quite graceful, less entropic, fosters the single responsibility principle, and reduces coupling. The delegation pattern is seen throughout all of Cocoa, not just the UI classes, so you can expect to see it often.
To know about other objects, you pretty much have to visit the Framework Library Reference for the specific class at the Apple Developer Center or from within the help system of Xcode. You can almost presume that all data backed UI objects will have datasource (delegate) methods, and most UI objects will have delegate methods.