Notify all loaded ViewControllers of a certain event - objective-c

I have a class that synchronizes data in the background every once in a while. The user can be anywhere in the app's navigation tree and no matter where the user is I need to be able to update the view controllers with whatever new data I just synchronized.
I put the object in charge of the background thread sync as a property of the SharedAppDelegate.
In a way I need to implement something like the Observer pattern and every time I instantiate a view controller set it to listen to some event on the background sync object so that after every sync I can execute a method in the view controllers that are listening.
I'm not sure what the correct way to do this in Objective-C is or if there is even a better or recommended way.

Use a NSNotification with NSNotificationCenter, which fits precisely your purpose :
in your AppDelegate, when the sync ends, call
[[NSNotificationCenter defaultCenter] postNotificationName:#"SyncEnded" object:mySyncObject]
in every view controller you display, call
_myObserver = [[NSNotificationCenter defaultCenter] addObserverForName:#"SyncEnded" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){ ...your UI refresh code... }
also do not forget to remove the observer when it's not needed anymore (view controller deallocated / unloaded / not visible, up to you ), or the NSNotificationCenter will end up crashing :
[[NSNotificationCenter defaultCenter] removeObserver:_myObserver];
A few notes :
This example uses the block-based API to perform the UI refresh work on the main operation queue (implying on the main thread), because you must not perform UIKit operations on any other thread than the main thread. This is likely that your background sync will send its notification on an other thread, so switching to the main thread is necessary. If you want to use the selector-based API, be sure to send the notification on the main thread.
You can register as many observers on the notification as you want, so this matches perfectly your pattern (NSNotifications are usually the best way to notify different app components of an app-wide event like sync end).
The object parameter passed when posting the notification allows you to access the sync object in the observer block using note.object if you need it.

Related

NSManagedObjectContextDidSaveNotification best way to update the UI?

In my code i have an mainManagedObjectContext and a backgroundManagedObjectContext and its working great.
I moved all my save code to the backgroundManagedObjectContext and merging the differences between the contexts via NSManagedObjectContextDidSaveNotification.
Now I want to update my UI after NSManagedObjectContextDidSaveNotification. What is the best approach beside of a NSFetchedResultController to do this?
The changes in my object is visible via the debugger and I could use KVO for this, but IMHO it's a terrible idea. In my abstraction i got a Model to handle the database calls and it would be great when my Model also handling changes after merging the context.
What is the best approach to do this?
As has been pointed out, for table and collection views, the best bet is NSFetchedResultsControllerDelegate.
Another mechanism is to register for this (or your custom) notification NSNotificationCenter, e.g. for the original notification:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(updateUI:)
name:NSManagedObjectContextDidChangeNotification
object:nil];
Best do this in viewDidAppear. Don't forget to remove the observer in viewWillDisappear. Note that following the comment I am using the change notification rather than the save notification.
In your non-table view controllers you should isolate the UI setup, similar to the boilerplate code for the fetched results controller delegate, which implements a method like configureCell:atIndexPath:. You can then simply call this setup routine when you get the notification without duplicating any code.

how to receive NSWorkspace and accessibility notifications on another thread

I am trying to do window management, but I need the code running on a separate thread.
The first thing I need to do is subscribe to app notifications like this:
NSNotificationCenter *nc = [[NSWorkspace sharedWorkspace] notificationCenter];
NSString *not = NSWorkspaceDidLaunchApplicationNotification;
[nc addObserver:self selector:#selector(appLaunched:) name:not object:nil];
But if I simply call addObserver on another thread, will the notifications be delivered there instead?
Apple has this reference, but it seems overcomplicated:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Notifications/Articles/Threading.html
If the answer to the first question is no, then why couldn't I just forward the message like this?
NSThread *other;
- (void)appLaunched:(NSNotification*)not {
if([NSThread currentThread] != otherThread)
[self performSelector:#selector(appLaunched:) onThread:other withObject:not waitUntilDone:NO];
else
// do respond to notification
}
The second thing I need to do is add an AXObserver to a runloop on the other thread.
If I call CFRunLoopGetCurrent() from another thread, will a run loop automatically be created like calling [NSRunLoop currentRunLoop] or do a I have to create one?
Observers which are registered using -addObserver:selector:name:object: receive the notification on the thread where it's posted, not where they registered. There's also -addObserverForName:object:queue:usingBlock:, which causes the notification to be received on the specified queue, but that doesn't let you make it arrive on a specified background thread. (Only the main queue is tied to a thread.)
You can shunt a notification to another thread in the manner you suggest. However, the original receiving thread has to be idling to receive the notification in the first place. Or, rather, it has to be idling in order to allow NSWorkspace to detect the condition which causes it to post the notification.
All threads create a runloop for themselves as soon as it's requested. It's basically impossible to observe a thread not having a runloop, so you might as well just act as though the runloop is created when the thread is created.
All of that said, your original goal – "I am trying to do window management, but I need the code running on a separate thread" – is problematic. Many GUI manipulations are not legal from background threads. Also, why do you "need" to do it from a background thread? And if your main thread is not free, you're not going to receive the workspace notifications in the first place.

Utility of notification 'UIApplicationDidEnterBackgroundNotification'

I am using Cordova 2.1.0 for IOS app development. Since, I am new to app development, I have a very basic question.
I am using applicationDidEnterBackground method to handle app control when app enters background. But i want to understand the utility of UIApplicationDidEnterBackgroundNotification which is sent when the app is entering the background. In what way can i use this notification and other notifications(like UIApplicationWillEnterForegroundNotification, etc.) sent by the system. What is the USP of these notifications.
According to the documentation, the method applicationDidEnterBackground: tells the UIApplication's delegate that the application is now in the background. In Cocoa, many delegate messages have corresponding UINotifications that are also sent. This is no exception.
According to the documentation:
The application also posts a UIApplicationDidEnterBackgroundNotification notification around the same time it calls this method to give interested objects a chance to respond to the transition.
Therefore, if there are objects in your object graph that need to respond to the state transition, they can observe this notification. I'm not sure there's really an unstated purpose beyond allowing all objects in the graph to respond to application state transition. I suppose if you had a long-running task to perform somewhere down the object hierarchy when the application transitions to background task you could use beginBackgroundTaskWithExpirationHandler: in a manner similar to what you do in the applicationDidEnterBackground.
EDIT:
// example, save NSArray *_myArray to disk when app enters background
// this is contrived, and untested, just meant to show how you can
// observe the UIApplicationDidEnterBackgroundNotification and save state
// in an arbitrary point in the object graph. (as opposed, or in addition to, the
// application's delegate.
// long-running tasks, e.g. web service connections, etc. will need to
// get a background task identifier from the UIApplication and manage that.
__block id enteredBackground = nil;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
enteredBackground = [center addObserverForName:UIApplicationDidEnterBackgroundNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[_myArray writeToFile:#"/path/to/you/file" atomically:YES];
}];

Is it OK for a view to know about its controller?

I'd like my controller to subscribe to notifications from view. However, before doing that, I'd like to confirm if it is OK for a view to know the instance of its controller?
Let me offer you a more specific example of what I have in mind.
My controller creates the view and informs it that it is its controller
self.gameView = [[GameView alloc] initWithController:self];
Once done, it subscribes for notifications from this view
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(saySomething:)
name:#"SaySomethingClever" object:nil];
Meanwhile the view does its thing, but when the right time comes, it posts a notification
[[NSNotificationCenter defaultCenter] postNotificationName:
#"SaySomethingClever" object:gvc];
In order for it to do it, the view needs to know the recipient of the notification (gvc).
I'd like to use this opportunity and as you whether the following is ok:
When initWithController is called, the view
-(id) initWithController: (GameViewController* )g {
gvc = g;
return [self initWithFrame:CGRectMake(0, 0, 480, 300)];
}
where initWithFrame:CGRectMake is a private method that handles specific view stuff.
Everything works fine, however, i wonder whether this approach is morally acceptable
It's not strictly a problem if the view has a reference to its controller, but it looks like your real problem is a misunderstanding of the notification posting method.
The object argument isn't the receiver. Indeed, if it were -- if the poster of a notification had to know the object that was going to get the notification -- that would defeat the entire purpose of the notification. You could just call the appropriate method! The point of notifications is that the poster doesn't need to know the other objects which are listening.
The object argument is actually used by the receiver to distinguish which notifications it should care about. Most frequently, the argument is the poster itself:
[[NSNotificationCenter defaultCenter] postNotificationName:IDidSomethingInteresting
object:self];
but it can in fact be any object.
When registering for notifications, you can specify a particular instance whose notifications you're interested in. This is the object argument to addObserver:... The notification center will then only pass on those notifications whose name and object match what was specified.
Even if you pass nil for the object in addObserver:..., you can check the object of a received notification and only act if the poster was one that you are interested in.
For example, there might be several windows in you application, and you may be interested in knowing when one of them is resized, but you don't care what happens to the rest of them. You would pass just that window instance as the object for addObserver:...
To sum up, your view in this case doesn't need that reference to its controller in order to for the controller to receive notifications posted by the view.
See also: "Posting Notifications"
While the concept is OK, it's not needed in your case:
[[NSNotificationCenter defaultCenter] postNotificationName:#"SaySomethingClever"
object:self];
The object referenced by an NSNotification is usually the object which posts a notification. The whole notification idea is that posters don't need to know about observers.
I would focus on controllers calling other controllers (or ideally model methods).
Allow each view to work with it's main resource and allow the controller for that view to make additional calls.

NSManagedObject: create on separate thread

I understand that Core Data is not thread safe and that NSManagedObjectContext and NSManagedObjects associated with a context cannot be passed from thread to thread.
Question:
However, if I have a NSManagedObjectContext on my main thread, can I create a NSManagedObject object on a background thread (WITHOUT attaching it to any context -- that is, simply call alloc/init on NSManagedObject), then pass that NSManagedObject back to the main thread and add it to the context from there? I've reviewed the docs on Core Data concurrency, but can't find anything that says this usage pattern is okay.
Context:
I have a background thread that performs a complex task and then publishes a result. The result is an NSManagedObject subclass that contains a few attributes: time, a file path, and a success or error message (as a string). I want to create the result object on the background thread, then toss it back to the main thread and add it to the Core Data context where it will be displayed in a tableView.
If I can't create the managedObject on the background thread, then I'll need to create a dictionary, pass the dictionary to the main thread, read the keys, create the managedObject from those values, etc. Just seems cleaner to create the managedObject on the background thread if possible.
The better approach is to have a context per thread. This way each thread will have its own scratch pad to play around with. Then when you background thread finishes, tell your main thread to update its view or ui table view or how every you are presenting your data.
You'll need to notify your main thread when changes occur. The big problem is, the contexts between different threads and main thread are not aware of each other. There is a way in core data to keep the contexts in sync. When you want to save, the context on the background thread should broadcast an NSManagedObjectContextDidSaveNotification notification.
So for example, in your main method in your NSOperation, you could do this:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:context];
the mergeChanges would be a private method in your NSOperation instance.
example of merge changes
- (void)mergeChanges:(NSNotification *)notification
{
ApplicationController *appController = [[NSApplication sharedApplication] delegate];
NSManagedObjectContext *mainContext = [appController managedObjectContext];
// Merge changes into the main context on the main thread
[mainContext performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
}