NotificationCenter or Closure? - swift

For the supervisors: I have searched a lot before I decided to ask
this question but I didn't find exactly what I want.
My question is: Which is better between using NotificationCenter and using Closures to communicate between two instances?
If they are similar, what should I use?
Hopefully, this example helps you to understand better:-
If we take URLSession class as an example. Why do most of its methods have a closure? Why do not they send a notification with Data, Response, and Error inside it?
I know the difference between them, I just don't know in what situations should I use each one.

In some cases the patterns are interchangeable, however:
Using a closure is the simplest solution for simple cases
Using a delegate is common when there is complex communication between two objects. One delegate can be better than many closures.
You have to use notifications when you have multiple observers or when you are not sure what objects will be observing.
You might be asking yourself why we are using closures for simple cases and not delegates or notifications. The answer is that closures are the most lightweight. They are easy to create and they positively affect your code quality.
Let's consider a completion callback. If you decide to use a notification, you need another method that will handle that notification. The same is valid for delegates. If you need some context (e.g. the parameters that triggered the actions), you will need to save it into a property.
On the other hand, a closure can be created inline. That means that the code that triggers the action and handles its result is at one place. This really simplifies the structure of your code. Also note that if the closure needs some context, it can capture it, without the need to create an additional property.

Related

iPhone - delegate or notification?

You have a class that has to send a message to its parent. This class is not used by any other member of your application. You send the message as a NSNotification or you create a delegate protocol on that class and implement the delegate method in the parent, so you can send the message?
What is the best approach and why? There's any advantage of one method over the other?
Thanks
Notifications is useful for when you have multiple observers or objects that are interested in the notification. They're also useful for Key Value Observing.
Delegates are very useful for sending a message (which conforms to the protocol that you declare) from one object to another object designated as the delegate target.
While both approaches could be used to satisfy the described messaging requirement, a delegate protocol is the better suited choice in this case.
The benefit of notification as pattern is that many objects may respond to a notification which has been posted. An object wishing to observe notifications need only register to receive them. An advantage to this is that your code is very loosely coupled (generally a desirable value in oop). The drawback to the loose coupling in this case is the fact that you have potentially related behavior occurring across different classes and essentially all over your code base.
A delegation pattern is more tightly coupled, and your delegate object must conform to the protocol of the object it will receive messages from. Because of this, it is relatively easy to observe the nature of the interaction (or intended interaction) between the notifying object and the notified object - it's easier to grasp, simply by looking at the code, object messaging between two "related" objects. In a case where you have a child essentially announcing some behavior (which is directly related to the behavior of the parent, presumably), I think delegation is a superior approach.

Callback from static library

I think this should be simple, but im having a real hard time finding information about this topic. I have made a static library and have no problem getting the basics to work. But im having a hard time figuring out how to make a call back from the static library to the main APP.
I would like my static library to only use one header as front, this header should contain functions like:
requestImage:(NSString *)path;
requestLikstOfSomething:(NSSting *)guid;
and so on..
These functions should do the necessary work and start a async NSURLConnection, and call back to the main application when the call have finished. How do you guys do this, what are the best ways to callback from a static library when a async method is finished? should i do this with delegates (is this possible), notifications, key/value observers. I really want to know how you guys have solved this, and what you regard as the best practices.
Im going to have 20-25 different calls so i want the static library header file to be as simple as possible preferable only with a list of the 20-25 functions.
UPDATE:
My question is not how to use delegate pattern, but witch way is the best to do callbacks from static librarys. I would like to use delegates but i dont want to have 20-25 protocol declarations in the public header file. I would prefer to have only one function for each request.
Solution choosen:
i choose the solution from erkanyildiz with the help of a target parameter, i know its pretty low tech, but it was for me the cleanest solution. My goal was to keep the header file as small as possible. Thanks to everybody for they input, i will for sure look more into borrrdens solution with grand central dispatch when i get the time. user1055604 solution with a couple of "standard" delegates for replys is also one i like. So again thank you all for inputs.
Thanks in advance.
Best regards
Morten
Delegation pattern is a good way to do it.
You can check these pages:
http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW18
http://en.wikipedia.org/wiki/Delegation_pattern#Objective-C_example
As another approach, you can use a target parameter in every method you have.
And schedule callbacks on those targets, checking if they are responding to your callbacks using respondsToSelector
Look here for an example with delegates: How to perform Callbacks in Objective-C.
It shouldn't matter that the callback is executing from within a static library.
Static libraries are a compile/link time phenomenon. As such, calls to and from within static libraries are transparent to the application at runtime.
If you would rather not have one callback protocol declaration for each function in your static library, start with looking at what each callback would return if you did, forcefully, implement it as a callback.
From there on, find what's in common between them and bind the common elements together in a class which will serve as an interface for the responses. You may need more that one such class.
As an example, look at NSURLResponse:
NSURLResponse declares the programmatic interface for an object that accesses the response returned by an NSURLRequest instance.
NSURLResponse encapsulates the metadata associated with a URL load in a manner independent of protocol and URL scheme.
This class is used by NSURLConnection in its didReceiveResponse delegate method. In the worse case, you will end up with a couple of callbacks instead of a noisy header file. Happy coding. :-)
Try making your function calls using Grand Central Dispatch. It's quite simple, and very powerful. Here is a sample of how to make an async call with a callback:
http://pastebin.com/xDUKm6wh
This paste bin is complaining about errors, but take note of the pattern. It should work just fine.

What is NSNotification?

Can anybody explain the importance of NSNotificationCenter?
Where to use them?
What is the difference between NSNotificationCenter vs. AppDelegate?
Apple has provided an Observer Pattern in the Cocoa library called the NSNotificationCenter.
The basic idea is that a listener registers with a broadcaster using some predefined protocol. At some later point, the broadcaster is told to notify all of its listeners, where it calls some function on each of its listeners and passes certain arguments along. This allows for asynchronous message passing between two different objects that don't have to know about one-another, they just have to know about the broadcaster.
You can find more details about it here: http://numbergrinder.com/node/32
The Application Delegate is an object which receives notifications when the UIApplication object reaches certain states. In many respects, it is a specialized one-to-one Observer pattern.
You can read more about it here: What is the AppDelegate for and how do I know when to use it?
If you come from an Actionscript background then NSNotification is like adding listeners to objects I guess.
NSNotification is like notifying the other class about the changes that will happen if some action takes place in another class.

iphone RESTful webservices

Not even sure if the title is correct, however, what I'm trying to do is use the standard NSURLConnection class to handle responses from calling my webservice. I am using the POST method to update a database and the GET method to retrieve rows from the database. The problem I have is that these 2 actions may occur simultaneously so that the methods to handle the request may step on each other. In other words in my "connection didReceiveData" method I have 2 paths through the code depending on whether I'm handling a response from a GET or POST request.
I keep track on which request in being processed by an instance variable called requestType. The problem is that since the requests are being executed simultaneously the instance variable is being changed from GET to POST before the GET completes (or vice-versa). My question is how do I maintain 2 separate requests in this scenario? Do I synchronize the requests? Is there a way for threads to work here? Do I create 2 separate objects for each of the requests and have the logic in "didRecieveData" query for which object is being processed? Any help would be much appreciated!!
Dealt with a similar issue in one of our apps. The solution involved creating a class that represents a webservice call, responsible for calling its own url, loading its own data, etc. The call class had a delegate that would handle parsing the responses (in our case, a web service controller). Wound up getting rather complicated, but prevented the issue of NSURLConnections stepping on each other.
Seems like you've created a messy problem by having a class that tries to do too many things. I would suggest taking one of the following three approaches:
1) Write two classes, one for updates and one for retrievals. Each class creates it's own private NSURLConnection object and acts as the delegate for the async notifications received from the NSURLConnection. The classes could possible share some utility parsing code or extend a base object that has that parsing code in it. But the key being that the code calling these classes would instantiate one of them, make the call, and then release it. This will keep your code cleaner and will insure that the event notifications don't get intermingled.
2) Create a single class that, depending on initialization, does either a post or a get with it's own private instance of NSURLConnection. When a call needs to be made, instantiate the class, get the results, and then release the class.
3) Write your connection handling classes so they use the synchronous NSURLConnection method and call that call that class in a background thread.
Either way, clean code and clear object orientation will prevent messy scenarios like the one you're describing.
Create separate objects that handle the calls. If you want to issue multiple requests at once I would strongly recommend looking at NSOperationQueue, and making these objects subclasses of NSOperation... much nicer way to deal with multiple background requests.
A good example is here:
http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
The idea there is that you use the non-asyncronous web calls, in operations that are run on separate threads. You can still use asynch calls in NSOperation as well, but doing so is a little trickier and for simple calls you probably do not need to.

NSNotificationCenter vs delegation( using protocols )?

What are the pros and cons of each of them?
Where should I use them specifically?
The rule of thumb here is how many clients would like to be notified of an event. If it's mainly one object (e.g. to dismiss a view or to act upon a button clicked, or to react to a failed download) then you should use the delegate model.
If the event you emit may be of an interest to many objects at once (e.g. screen rotated, memory usage, user login/logout), then you should use the NSNotificationCenter.
Their purposes are different:
Notification is used to broadcast messages to possibly several recipients unknown from the sender.
Delegation is used to send messages to a single known recipient acting on behalf of the sender.
Notifications are generally better for notifying the UI of changes the occur on other threads as well. Apple's documentation strongly discourages the use of delegates across threads where possible, both for stability and performance reasons. On the Mac, they suggest using Bindings, but since they don't exist on the iPhone, notifications are probably your next best bet.
Considering the performance is a good idea (delegation better for small number of notified objects, notification centre better for larger number of objects, or is it? run a profiler) but I think a more important factor since you are talking about Objective-C and less likely to be talking about the really high performance parts of your code base, which are likely to be written in C, is reducing compile-time dependencies between modules.
There is nothing to stop you having an array of delegates rather than a single delegate.
I might use NSNotificationCenter only for status of any network stack components I make and any custom device status monitoring interfaces. But for most coupling, not to do with global status of the app, I think it is clearer to use normal interface contracts in Objective-C in most cases and easier to folow for the people coming after you than to use NSNotificationCenter. In fact I have never used NotificationCenter for my own custom events and prefer to use delegates for ease of code comprehension by someone else reading my code.
And finally, of course with notifications to/from the standard API you don't have choice and must use whichever of the two methods Apple proscribe for a given event.
Notifications are better for decoupling UI components. It allows you to plug any view without any modification in your controllers or models. Definitely better for loosely-coupled design.
But for the performance between delegation and notification, you need to think about the frequency of the call.
Delegation might be better for more frequent events, notifications are better for less frequent events but more recipients. It's up to project what to pick.
An option in between those two is using the observer pattern, without NSNotificationCenter. Look at my Objective-C implementation here.