Are there any race condition issues when using NSNotifications within a single thread? Here is a sample method:
- (void) playerToggled: (NSNotification *) notification {
if (timerPane.playing && ! timerPane.paused) {
[playerPane toggleCurrentPlayer];
[timerPane toggleTimer];
[mainPane playerToggled];
}
}
The first two calls after the condition will trigger NSNotifications that will be received by mainPane. Is mainPane guaranteed to receive the playerToggled message after those notifications? I should say that this code seems to work as desired (playerToggled always executes last). But I'm not sure what timing issues there are around notifications and I can't find a specific answer.
There are no race conditions to be expected. In addition to Dan Donaldson's answer, here is another quote from the docs for NSNotificationCenter:
A notification center delivers notifications to observers synchronously. In other words, the postNotification: methods do not return until all observers have received and processed the notification. To send notifications asynchronously use NSNotificationQueue.
I am not exactly sure what you mean, but I think this will be helpful to you:
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Notifications/Articles/NotificationQueues.html#//apple_ref/doc/uid/20000217
Especially this part:
Using the NSNotificationCenter’s postNotification: method and its variants, you can post a notification to a notification center. However, the invocation of the method is synchronous: before the posting object can resume its thread of execution, it must wait until the notification center dispatches the notification to all observers and returns.
Related
Hi I have a problem with notificationCenter. I'm launching the load of three different feeds and I'm registering three notifications with three different selector (the observer object is the same for the three notifications).
notification1 -> selector1
notification2 -> selector2
notification3 -> selector3
All works fine but I can't unregister the observer when I receive the feed content because in that case i'm blocking to receive the other two feeds. otherwise if I don't unregister the observer I'm getting the notification twice if I resend the same query with the same selector and notification name.
Are there any way to unregister just the selector without unregister the object?
- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender
is the method you're looking for. Just pass the correct notificationName for each case.
I have created a library which can download JSON data which is then placed into an NSDictionary. I wrap this class with a simple Twitter engine which allows me to pull my friends timeline, post an update and post an update with my GPS location. From my limited experience with Objective-C the way to connect everything is with delegation. I set a delegate property which calls back the asynchronous result to either a selector or a method signature. I can even create an optional or required interface on the delegate which will allow Xcode to assist me a little with implementing the delegate. To learn about using delegates in Objective-C I created this simple project.
http://www.smallsharptools.com/downloads/ObjC/Delegates.zip
It defines a Worker class which allows you to initialize the class with a delegate. When the work is done with the doWork method it looks for a method signature on the delegate to send a message back to it. It uses the following code.
if([[self delegate] respondsToSelector:#selector(workFinished:)]) {
NSString *msg = #"That's it? Easy!";
[[self delegate] workFinished:msg];
}
It looks for the workFinished: method to pass back a message. I declared this method signature as an optional interface with the following code in the header, Worker.h.
#protocol WorkerNotifications
#optional
- (void) workFinished: (NSString *) msg;
#end
You can see the rest of the project from the download for all of the details. But these 2 code snippets show how this delegation pattern works. But with the Twitter class I need to know the context of the method which started an asynchronous action which leads to a callback to a delegate method. If I call the sendUpdate method more than once from the calling class, how I am supposed to know the context of the callback?
Normally with a language like JavaScript, Java or C# I would create an inline closure or anonymous class which would have access to the starting context, but that is not possibly currently with Objective-C on the iPhone. I found that this question was already asked and answered on StackOverflow.
Anonymous delegate implementation in Objective-C?
So what I have done is skip the optional interface and instead passed in a selector which the Twitter class will call when the asynchronous action is completed. A call to start this action looks like...
CMTwitterEngine *engine = [[CMTwitterEngine alloc] initWithDelegate:self];
[engine setSendUpdateFinished:#selector(sendUpdateFinished:)];
[engine setSendUpdateFailed:#selector(sendUpdateFailed:)];
[engine setParsingSendUpdateFailed:#selector(parsingSendUpdateFailed:)];
[engine setUsername:TWITTER_USERNAME pass:TWITTER_PASSWORD];
[engine sendUpdate:statusUpdateText.text];
This code first initializes the engine reference with self as the delegate. To attach the callbacks I send in selectors which I originally had on the sendUpdate method signature but the method calls got pretty long. I opted to simply set properties of the selectors. This all works but I am not sure I like how this is working since it only partially solves my problem.
To complete this example, I finish the asynchronous work and eventually call a method internally which looks for the given selector and calls it if it is defined.
- (void)sendUpdateFinished:(NSDictionary *)dictionary {
if (self.sendUpdateFinished != nil) {
[self.delegate performSelector:self.sendUpdateFinished withObject:dictionary];
}
}
I can pass in the status message to send as a Twitter update but I still do not have the context of the originating call. What if I want to call sendUpdate more than once and the first asynchronous call is still running? And what if the second call finishes first? They will both have self as the delegate so I would have to either track the context somehow or pass them to a different selector to distinguish them, which also does not satisfy my needs. What happens if I have 3 or 4 or 5 asynchronous calls? I need to know which ones were sent successfully and when they are complete.
It appears the only way that I can do all this is to create a class which holds onto all of the properties needed for the context, have that class act as the delegate for the call to the asynchronous Twitter method and then report back to the parent class which is likely UIViewController. I would take this approach but I have not read about this approach or seen any sample code yet which does this.
What would you do? How would you handle multiple asynchronous calls going out which could end in a different order than going out and then process them with context upon completion?
I think your situation is a great place to use NSNotificationCenter
http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html
I have to second (or third) the previously posted answers in that NSNotificationCenter is probably what you're looking for here.
Essentially one typically uses notifications when there are potentially many delegates all of which need to do something in response to a single action or event that has occurred. Think of it as a one-to-many sort of delegation or an implementation of the observer pattern. The basic things to know are:
NSNotifications have a name that you define which is just an NSString. Notifications can be posted by name and objects register to receive notifications by name.
When a notification is posted a notificationSender object and/or userInfo dictionary can be provided. The notificationSender is the direct way of determining who posted a given notification when it is being handled by the receiver. The userInfo is an NSDictionary that can be used to provide additional context info along with the notification.
So, rather than forcing all of the workers to adopt to an informal protocol and messing around with reflection style calling-methods-at runtime you just register instances of the workers with NSNotificationCenter. Typically the registration with the NSNotificationCenter is done in an init method of each worker class. Instances of each type of worker are then typically set up as "freeze dried" objects in a NIB or can be programatically instantiated in the app delegate so that they get registered with the notification center early on in the app's life.
When the thing occurs you post a NSNotification to the NSNotificationCenter (which is essentially a singleton) and then everything else that has registered to receive that particular type of notification will have the method called that was specified to handle that type of notification. When done these methods can then call a common method back on the sender (obtained via NSNotification's object method) to tell the sender that they've completed their work.
Once each known worker has checked in the the common method on the sender can then go on to whatever post-worker-completion code is to be performed.
One thing to consider is using Notifications instead. Simplifies code, couples things less tightly.
Are events posted by NSNotificationCenter postNotificationName processed before UI updating events?
I need to know because otherwise my current program will crash in some rare cases.
Model code:
- (void)searchFinishedWithResults:(Results *)results {
self.results = results;
// If some table cells are loaded NOW, before notication is processed, we might crash!
[[NSNotificationCenter defaultCenter]
postNotificationName:SearchResultArrived object:nil];
}
When processing the notication, I will run UITableView reloadData.
However, consider if before processing the notication, UI has to be updated. In this case -tableView:cellForRowAtIndexPath:indexPath will be called, but results object has changed, it will fetch old data.
The notifications are dispatched exactly when you call postNotification: or postNotificationName:object:, in a synchronous fashion, one observer after the other (in no particular order). In the case you show, they would be sent exactly after you assign the variable "results" and before the method ends.
Directly from Apple's documentation on NSNotificationCenter:
A notification center delivers
notifications to observers
synchronously. In other words, the
postNotification: methods do not
return until all observers have
received and processed the
notification.
To send notifications asynchronously
use NSNotificationQueue.
As an aside, I think you need to rethink your design. It sounds like you don't have sufficient separation between the view and the model.
Your data model should know what is and is not old data and should only return current data to the tableViewController. The data model should have complete control over the integrity of the data and it shouldn't be possible to force it to return the wrong data. It definitely should be impossible that the app will crash owing to such forcing.
I have set up an operation queue and an invocation operation. Do I need to signal that the invocation is commpleted? If not how will the operation queue knows the invocation is finished and move on to the next one? The operation queue has been set to execute one operation at a time.
No, there is no need to signal that the invocation has been completed. An NSOperationQueue knows that an operation is finished when its isFinished property is set to YES. This happens by default when the operation's -main method returns.
NSInvocationOperation's -main method, for all intents and purposes, just invokes its NSInvocation and returns, so its isFinished flag should be set to YES immediately after the invocation completes.
Boon,
It seems like what you really want here is to subclass NSOperation yourself and call your asynchronous inside of it. When the async code completes and you get your callback, you would then notify the queue via KVO that isExecuting and isFinished are updated. This is explained much more in detail over at Dave Dribin's blog:
http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
It's automatic for NSInvocationOperation. You're already good to go.
If you need to tell other parts of your app that the operation has completed, you can use a notification. Be sure the notification goes to the right thread. On the iPhone, I send them to the main thread because I often change the UI in response to a notification, and all UI stuff must happen on the main thread.
[self performSelectorOnMainThread:#selector(postOpDoneNote) withObject:nil waitUntilDone:NO];
-(void) postOpDoneNote
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"someOpDone" object:self];
}
What's the code to subscribe to an event like applicationWillResignActive in any place in your iphone application?
[UPDATE]
Let me rephrase my question. I don't want to respond to this in my application delegate, but rather listen to this event from another class. Is that possible or I need to pass the event from the application delegate to the concerning class?
Looks like you are looking for this code.
- (void) applicationWillResign {
NSLog(#"About to lose focus");
}
- (void) myMethod {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(applicationWillResign)
name:UIApplicationWillResignActiveNotification
object:NULL];
}
Take a look at the documentation for the method you're talking about:
applicationWillResignActive:
Tells the delegate that the application will become inactive. This method is optional.
- (void)applicationWillResignActive:(UIApplication *)application
[...]
Discussion
[...]
Just before it becomes inactive, the application also posts a UIApplicationWillResignActiveNotification.
Implement the method below in your application delegate:
-(void)applicationWillResignActive:(UIApplication *)application
This allows you to react when the application becomes inactive - when this is the case, it is executing but not dispatching incoming events. This happens, for example, when an overlay window pops up or when the device is locked.
Just before it becomes inactive, the application also posts a UIApplicationWillResignActiveNotification.
Your topic and question are asking slightly different things.
Your application will receive applicationWillResignActive, along with applicationWillTerminate, automatically. No subscription is necessary, just implement the function in your app.
As to how to respond, this is down to the application. While you can choose to do nothing the recommended behavior is that you cease or slow any non-critical functionality. E.g. if you were a game you would stop updating the display and/or pause the game.