What is NSNotification? - iphone

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.

Related

NotificationCenter or Closure?

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.

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.

asynchronous request objective c

hi i am developing a sms App for my client. so far i have put down this plan in place.
1)The app keeps polling the server with an asynchronous request so that it does not interfere with the user interface.
2) for sending sms i am currently using synchronous request , depending on the reply from server i have do various things. i am showing the spinning circle and make the user wait until i get the response from server.
my client has problem with point 2.
The client says as soon as the send sms button is clicked it has to go back to the homescreen and should be able to navigate to any screen and do all other things that the app offers. i could have used async request , but i am not sure how to handle the responses from the server when i am on different view controller other than the one request is called from.
Can somebody help me on this.
Thank You.
The classic way of handling the response of an asynchronous action is either using delegation or notifications. Do not use a singleton. This breaks modularity and decoupling of different view controllers.
Roadmap of how to handle asynchronous actions
Register for the response of the asynchronous actions. This can be setting the delegate of the requesting object e.g. NSURLConnection to the view controller, which is typically self in this context. The othe possibility is that you register for the notification which is fired by the requesting object if things have happend e.g. when a download is finished or an error occurred.
Implement the delegate methods or the notifications to update your model and/or your user interface. Be aware that updating the UI has to happen on your main thread.
Start the asynchronous action. What happens in the background is that a separate thread is spawned or an operation is dispatched using GCD. These are implementation details and do not bother you.
Wait for the answer, which will result in one of your implemented methods to be executed which you then use to update what has changed.
Difference between notifications and delegates
The two differences between delegates and notifications is that delegate is a one-to-one connection between the delegate and the delegating object. Notifications are posted application wide and can be observed by as many objects as needed creating a one-to-many connection. Think about this as a broadcast. The second main difference is that delegation can be used to transfer information back from the delegate to the delegating object. Meaning that the delegating object asks the delegate for certain information. Typical example would be the data source of an UITableView. Notifications however are a one way street. The information flows from the posting object to the observing objects. This makes sense because think about the situation where you would have more than one observer and each would give feedback to the posting objects. Which one would be the right one?
In your case you would have to look up the delegate methods of the asynchronous HTTP request object and implement them accordingly.
Maybe you can try ASIHTTpRequest , It has Sync an Async request
If you using Async request , you can do anything after you press a button to do a request .
Check this
The solution depends on the response processing.... if you are just showing user that the sms sending is failed/successful than you can do it in any general utility class that shows alert.. but for this you have to create the singletone instance of your connection class so delegate(class itself) don't die when the response comes back.......
For this we need to keep track of currentViewController ....... we can do this by creating a reference ........ id currentViewController in appDelegate(with setter/getters).......... so it could be accessible in everywhere application........
its referred object should be changed each time when user changes the viewController.... that will help us to know on which viewController user is currently working.
than when the singeltone class of connection finished its response loading we can use this currentViewController with your desired viewController.
I am not sure how you are using different view controller....... pushing it/ presenting it or adding its view.....

iPhone Objective-C service handlers

I am a as3 developer, I am used to use handlers everytime I launch an event and I am wondering which is the best way / practice to do that in Objective C.
Let's say I want to call a diferent services from my backend.
In as3 would be something like this to listent to the finish event:
service.addEventListener( Event.COMPLETE, handler_serviceDidFinished )
service2.addEventListener( Event.COMPLETE, handler_serviceDidFinished2 )
But how can I do the same in Objective C?
The problem is I already created the protocols and delegates, but how can I separate each response from the server?
For example:
-(void)callService:( NSString * )methodName withParameters:(NSMutableDictionary *) parameters
{
...
if (self.delegate != NULL && [self.delegate respondsToSelector:#selector(serviceDidFinishSuccessfully:)]) {
[delegate serviceDidFinishSuccessfully:data];
}
}
Well I'm trying to create a generic delegate here, so how can I separate each response for every service?
My first idea is that maybe I should return the name of the service method in the delegate call to identify each service. Maybe I should create a UID for each service and pass it the same way...
Any idea?
You might be interested in Objective-C notifications. Basically, these allow you to use a "notification center" to which you "post" different messages; then, all the callback/delegate classes can "register" for certain notifications, so that they know when to do things. This way, all your backend has to do is post the notification, and not worry about whether certain delegates respond to selectors, etc. See Cocoa Core Competencies: Notifications (as well as the NSNotificationCenter and NSNotification class references) for more.
Look at the NSURLConnection delegate - the common pattern is to pass back the object calling you as the first parameter, exactly so you can distinguish among several objects you are a delegate for.
Notifications are a useful thing to indicate task completion, but not really good for handlers that need to affect the processing flow of the object.

How can I listen for didRegisterForRemoteNotificationsWithDeviceToken outside the app delegate

I would like to my object to receive notification with the DeviceToken becomes available. Is there a way to delegate only certain functions from the UIApplication to my class?
Update:
I'm not so much interested in accessing it from the application delegate, I already have an application delegate, but want to respond to the event via call back or some observer method if it's possible.
Despite not being marked as such in the documentation, all UIApplicationDelegate methods are optional, so you can simply implement the ones you require, and ignore the ones you don't.
However, you'll probably want to implement all three of the APS methods, rather than just the one indicating registration success!