How does UIApplication take an event from the top of event queue - ios

I read this in the official doc:
First, the singleton UIApplication object takes an event from the top of the queue and dispatches it for handling.
How does this happen??
Also in the doc there is this section:
An App Receives Touches in the Touch-Handling Methods:
During a multitouch sequence, an app sends these messages when there are new or changed touches for a given touch phase; it calls the
touchesBegan:withEvent: method when one or more fingers touch down on the screen.....
Can somebody explain this line"..an app sends these messages...". It is very ambigious as to which "messages" are being talked about in the doc!!!!
Doc link:https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizer_basics/GestureRecognizer_basics.html#//apple_ref/doc/uid/TP40009541-CH2-SW2
Also, how internally does the UIApplication send the events to keyWindow??
Does it use sendEvent or does it have code something like
[[self keyWindow] touchesBegan:touches
withEvent:event];

How does this happen??
A queue is a first-in-first-out data structure. You put things in one end, and you take them out on the other. Exactly what method gets called to do this depends on how the OS happens to implement the event queue, but in the end it really doesn't matter at all, and in fact it may be done differently in different versions of the operating system. The event queue is an implementation detail, so you shouldn't make any assumptions about how it works.
Can somebody explain this line"..an app sends these messages...".
It just means that the app calls certain methods on certain objects. In Objective-C, "sending a message" is another way of saying "calling a particular object's instance method." If you have:
[foo bar];
you are sending message bar to foo.

Related

Passing NSNotifications. Good? Bad? NBD?

I'm trying to think through the ramifications of passing an NSNotification object as a var to a method.
It seems like it's difficult to trace what happens to a the flow of logic with a notification anyway (without some great commenting and method/object naming) so passing the notification to another method/class/lib/project would just make it even less fun to debug or respond intelligently to an error.
But it just feels like it's the sort of thing that has a lot of hidden gotchas potentially.
And I know there are still a lot of people out there who love notifications.
So does anyone have some pros/cons/better-practices about passing the actual NSNotification object as a var between methods?
Just for clarity's sake here's some pseudo code:
[[NSNotificationCenter defaultCenter] postNotificationName:kSuperImportantNotification object:self userInfo:soMetaDict];
... Later in the code:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(importantThingHappened:) name:kSuperImportantNotification object:nil];
... Later in the code:
- (void) importantThingHappened:(NSNotification *)notification {
[respondingInterestedClass executeSomethingWith:notification];
}
... In "respondingInterestedClass":
- (void)executeServicesDiscoveredBlock:(NSNotification *)notification {
// ... do something with the NSNotificaiton object.
}
Thanks
It depends in what you are doing, usually this is when to use what:
One-to-One relationship and loose coupling: Delegate
One-to-One relationship and tight coupling: Direct method calls
One-to-Many relationship and loose coupling: Notifications
One-to-Many relationship and tight coupling: KVO
So you should not use Notifications for all kind of communication, lot of developers use them heavily even when its not needed.
Saying this, it is totally fine to pass the notification object to the method handler, but don't pass it anywhere else.
Putting aside how and when notifications should be used and focusing purely on the ephemeral set of uses that are totally the right choice....
Once received, the notification object is a state container that contains some set of state in a format that is convenient to the system. You can shoehorn whatever you want into it by shoving key/value pairs into a dictionary and passing it as the userInfo, if you want, but it is still the system state.
In a well designed body of code, there are hard fought barriers through which the format of the data and the encapsulated messaging are well defined. In a Model-View-Controller system, for example, a Model class won't be a subclass of UIView or handle user events directly.
And Notifications should be treated the same. When the notification is received, unwrap it into whatever internal-and-specific-to-your-architecture representation you want and pass that around.
Or, consider:
- (void) somethingChangedNotification:(NSNotification *)changed
{
[myModelGoop applyChange:...];
}
#implementation MyModelLayer
- (void)applyChange:(....)change
{
}
In the above, you could certainly pass the notification object into the model layer. But that's just pushing a system specific implementation detail into your model.
What happens the moment you have changes that aren't triggered via an NSNotification? Your either left to encapsulate your change into a fake NSNotification instance (because posting a notification may have side effects depending on who is observing) or you have to refactor the above to no longer take a notification in the model layer.
Better to get rid of the dependencies on system encapsulation early.
To that end, the NSNotification instance should never be passed out of the method that handles the notification.

What comes first applicationWillResignActive app delegate method or the Notification for the same event?

In my app delegate I save(persist) an object when the applicationWillResignActive: method is called. I have a view controller which responds to UIApplicationWillResignActiveNotification and makes a modification to the previously mentioned object but doesn't save(persist) the object itself.
What I need to know is if that change will be persisted trough the applicationWillResignActive: method or if I should explicitly save it in the view controller just to be sure?
Edit: NSLog test result is: 1st is the delegate method, 2nd it is the Notification method.
I wasn't sure the test would guarantee me that the order will be the same every time because I don't know how notification center works. That is why I posted the question before testing and giving results.
The documentation for applicationWillResignActive: says, "After calling this method, the app also posts a UIApplicationWillResignActiveNotification notification to give interested objects a chance to respond to the transition."
The "after" makes me believe that you will not get the changed value inside applicationWillResignActive:.
Of course, inserting a couple of NSLog lines would let you prove the order of operation for yourself.

UIApplicationDidBecomeActiveNotification and viewWillAppear causing Data Source conflicts

In my view controller I am calling a method to request data to populate my tableView and handle any notifications at viewWillAppear and also with a notification observer for UIApplicationDidBecomeActiveNotification.
This appears to cause problems when I am initially launching the app (not from the background) because my loadJSON method gets called twice, causing cellForRowAtIndexPath to crash as my data is changing.
Anyone have a suggestion on how this is typically handled?
You can test you loadJSON task is or not is executing before call it.
Or you can cancel privious loadJSON task before perform it.
I use global object to manage data, that I should download from different places.
My object (for example, named DataManager) has notifications, block-callbacks or delegate to notify listeners about data updating.
Also it has method to check his state, for example: isDownloading. If my DataManager more complex class, it has enum for states or many methods for any aspect.
Now I do not like to use Singleton for implementation of DataManager, I prefer to creating a property in AppDelegate to store instance of the manager inside.

How to update UI before nsoperation will start and or end

2 part question but related so will keep in the same thread:
I'm adding NSOperations to a NSOperationQueue. I need to know when the operation will start and when it ends in order to update the UI.
I thought about adding a "start handler" block to run in the nsoperation as well as a "completion handler" in the NSOperation
Something like
-(id)initOperationWithStartBlock:(StartBlock)startblock completionBlock:(CompletionBlock)completionBlock
but believe that there is a better way to get this from the queue itself.
How can this be done?
I would also like to know the index of the job sent by the NSOperationQueue.
I've tried doing
[[self.myQueue operations] indexForObject:operation]
but the index is always the zeroth index - because the completed jobs were removed from the nsoperationqueue array before I could check the jobs index.
Any way to preserve them?
You need to use Key-Value-Observing pattern in IOS. So for this you need to setup observers in your controller to look for changes to isFinished and isExecuting to catch start and finish hooks.
It depends if you want to perform something from within your object upon starting or elsewhere in your code. From what you are saying (you want to update the UI), this sounds like you want to act outside of your object, but I don't know your program. You have two options:
1) If you want to act in your object upon starting the operation from within the same object, use key-value observation and observe isExecuting with self as the observer and the observed. Don't forget that you will get called whether it goes from NO to YES (starting) or YES to NO (done).
2) If you want to perform an action outside of the object, I would rather recommend to use the very general NSNotification with NSNotificationCenter and within your main, post a notification such as #"willStart" and #"didComplete". In any other object, register as an observer for your notifications.
Either way, don't forget that notifications are sent in the current threads but the UI must be updated on the main thread. You don't know on what thread observe:keyPath: is called. You may need to call performSelectorOnMainThread to update the UI or you can even use the convenient and useful nsoperationqueue mainqueue with a addOperationWithBlock with your UI code. If you use the NotificationCenter, then you can simply yourself post on the main thread with nsobject performSelectorOnMainThread

Multiple Delegates in iOS

I am making an object that goes to download stuff for all of my view controllers. The object is singleton instance and has a callback method with received data once the download is completed. It also has a delegate property so that it knows which object to call back to after the download is done.
There are multiple controllers that use this shared instance, and my question is how to call back to the correct view controller that requested the download.
My approach is to use delegation, but the problem is that since other view controllers are also its delegate, the download object could call back to every object and this will be hard to track.
I've worked on projects where people have attempted to use multiple delegates and it's basically a bad idea. The delegate pattern is about a 1 to 1 relationship between a class and it's delegate. Whilst it is possible to achieve some level of multiple delegation through switching the delegates in and out, it's more likely to lead to unpredictable behaviour and bugs.
My recommendation would be to change how you are thinking about this. You have two options as I see it:
Switch to an Observer pattern where you can register multiple observers which your main class can interact with. This is useful where your observers all implement the same protocol and where your main class wants to be aware of the observers and interaction with them.
Broadcast NSNotifications to indicate state changes and events. Here is a more decoupled approach because the main class does not need to know who is listening and does not directly interact with them. Other can start and stop being notified at their leisure. It also has the advantage that you do not need to create or implement a separate protocol. Instead you register the classes that need to know about changes with the NSNotificationCenter which in turns handles all the routing of notifications for you.
It actually sounds like the delegate pattern might not be the best approach here.
I would look into NSNotificationCenter instead.
The basic idea is that your singleton doing the net connection posts a notification (with something like postNotificationName:object:userInfo:) , saying that new data is available. Within this notification, you can pass a dictionary object (userInfo) that holds the data you've fetched, or info on what parts of your Model contain updated data.
Then, your other view controllers can register themselves to 'observe' these notifications by calling addObserver:selector:name:object:. Generally speaking, when a vc becomes visible I call addObserver, and removeObserver when it's being hidden or transitioned out.
Good luck!
Delegation doesn't seem like the right solution to this problem. How about requiring the requesting view controller to provide an object (its self) and a selector for you to call as a completion notification? Of course, you'll need a place to store that object and selector until the download completes. Hopefully you have (or could create) an object for this.
i recommend to use one of these ways
observer:
when use data that you want to inform other object are near to primitive ones.for example when you are using 'NSMutableArray' you can not inform the change in one of object by the standard implemented pattern at least you need to implement one for your self that is not reusable that much
Notification
when your interaction with destination object (those need to be inform) is in one-way.it means you don't need any acknowledge or other data back from them.
delegate
when there is one object to inform at each time step.
note:block use for success and fail is not a pattern to broadcast data its about to queue task when you don't know when they are finishing or failing like network operations
EDIT:
how to create notification | multi delegate issues and implementation
While I agree with most of the answers here, if you did actually want to achieve multiple delegates you could potentially declare an array of delegates and send messages to all delegates within that array. If your protocol has optional delegate methods you safely check using responds(to aSelector: Selector!) -> Bool before invoking (being mindful of memory management, as those delegates would be strongly referenced in the array). Again I do agree that multiple delegates is likely a bad architectural idea and using blocks or notification center would suit your needs better.
One approach, which works for me if you only have one other object to forward messages to is to create a forwardingDelegate This does not end up with issues of hard to debug ordering of delegates and it does not unnecessarily create a dependency on the other object. Keep in mind, if you have many objects then this might not be the best approach, it is mainly for one additional object but this could be extended to support an array of objects so long as there is one that receives the SDK and forwards it to the other objects [1]. Note that every method that is needed for the forwarded object needs to pass it along, even if it is not used by the forwarding object.
For example, if I need to forward the messages coming from the mapView delegate:
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
// handle this object here.
if ([self.forwardingDelegate respondsToSelector:#selector(mapView:regionDidChangeAnimated:)])
{
[self.forwardingDelegate mapView:mapView regionDidChangeAnimated:animated];
}
// or handle this object here.
}
[self.forwardingDelegate mapView:mapView regionDidChangeAnimated:animated];
The forwarding property would be declared like this.
#property (nonatomic) id<MKMapViewDelegate> forwardingDelegate;
And the other object would adopt the protocol as if it were receiving the original message.
[1] The array approach for multiple delegates may get tricky because then you don't have as much control over what order the delegates get called, as was mentioned in other posts.

Resources