Is there any way to ensure that a class posts a particular NSNotification?
(I have a set of classes, and I would like to enforce at compile-time (if possible) that the class posts a required NSNotification).
Alternatively, if that is not possible, is there any workaround?
It's fundamentally impossible to predict at compile time what will happen at run time. The closest you can get is static analysis, but even that can't predict anything that happens outside of your own code, such as inside Foundation.
You can, however, do this with unit tests, since the test runner actually runs the code under test.
You'll need to create a test bundle target, if you haven't already. Your target will use SenTestingKit to run your tests, which you create. (On the iPhone, you'll also need Google Toolbox for, uh, Mac. They have a handy tutorial on using GTM for iPhone tests.)
You'll create a SenTestCase subclass to test whether your real object posts a notification. It'll look something like this:
#interface FrobnitzerNotificationsTest: SenTestCase
{
BOOL frobnitzerDidCalibrate;
}
- (void) frobnitzerDidCalibrate:(NSNotification *)notification;
#end
#implementation FrobnitzerNotificationsTest
- (void) testFrobnitzerCalibratePostsNotification {
Frobnitzer *frobnitzer = …;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(frobnitzerDidCalibrate:)
name:FrobnitzerDidCalibrate
object:frobnitzer];
frobnitzerDidCalibrate = NO;
//This should post a notification named FrobnitzerDidCalibrate with the receiver as the object.
[frobnitzer calibrate];
//If it did, our notification handler set frobnitzerDidCalibrate to YES (see below).
[nc removeObserver:self
name:FrobnitzerDidCalibrate
object:frobnitzer];
STAssertTrue(frobnitzerDidCalibrate, #"Frobnitzer did not post a notification when we told it to calibrate");
}
- (void) frobnitzerDidCalibrate:(NSNotification *)notification {
frobnitzerDidCalibrate = YES;
}
#end
You'll need one instance variable and one notification-handler method for every notification you want to test for, and one test method for every method you want to test for notifications.
Also, if using GTM, you must substitute GTMSenTestCase for SenTestCase above.
Related
This is not a trivial question asked here in StackOverFlow before, at least I haven’t found anything similar, of course I also googled it and read most of high ranked results.
BTW, if any folks here don't feel comfortable with Objective C’s block syntax, visit this page please
http://fuckingblocksyntax.com ,
before throwing any block related issues.
1st part of my question is: the background of declaration of block-parameter, as well as invoking a method which has a block-parameter ( in many cases, a completionBlock )
The “calleE-method" in MyWorker class:
… ...
#implementation MyWorker
-(void) aWorkerMethodNeedsABlockInput: ((void)(^)( NSObject *, double )) blockParam
{
NSObject *anObj=[[ NSObject alloc] init];
double *aDouble;
[self retrieveTimeConsumingResults: anObj withNumberOfTry: aDouble ];
blockParam ( anObj, * aDouble );
}
#end
The “calleR-method" in MyManager class:
#interface myManager()
#property (nonatomic) MyWorker * mWorker;
#property (nonatomic, copy) (void)(^mBlockProperty)( NSObject *, double );
#end
#implementation MyManager
-(void) aManagerMethodWhoCallsWorkerWithCompletionHandler
{
(void)(^ valBlock )( NSObject *, double ) = ^(void)( NSObject * realObj, double realDouble )
{
[realObj performSelector:#SEL( aSelector) withObject: #(realDouble) afterDelay: aTimeInterval];
} ;
self.mBlockProperty=[valBlock copy];
[self.mWorker aWorkerMethodNeedsABlockInput : self.mBlockProperty];
}
#end
above sudo-code was the NORMAL way, in our custom code, of storing a block inside property, declaring a block parameter and also offering block’s arguments in CALLEE; providing block definition and also “consuming” block’s arguments in the CALLER. I keep 'void' returnType in writing for clarity of block-syntax. Correct my writing if I did wrong, please!
2nd part of my question:
the routine usage of
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
NSLog(#"Handle events for background url session");
self.backgroundSessionCompletionHandler = completionHandler;
}
then later
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
WebAppDelegate *appDelegate = (WebAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.backgroundSessionCompletionHandler) {
void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
appDelegate.backgroundSessionCompletionHandler = nil;
completionHandler();
}
NSLog(#"All tasks are finished");
}
the background callback via the daemon works in above pattern based on NSURLSession framework, right? I did it many times, not a problem on applying such pattern.
Which I have been wondering for a long time is:
What is really inside the definition of the completionHandler parameter of “handleEventsForBackgroundURLSession:” method, when the method is invoked from a block-property storage? < at the time when “ completionHandler();” is executed >
I have never seen any sample/demo which put/copy any block-of-code into completionHandler... or I wish to know too much?
What is really inside the definition of the completionHandler parameter of “handleEventsForBackgroundURLSession:” method, when the method is invoked from a block-property storage? < at the time when “ completionHandler();” is executed > I have never seen any sample/demo which put/copy any block-of-code into completionHandler... or I wish to know too much?
If I understand your question correctly, you are asking what implementation is inside the block that is passed to an application's implementation of the UIApplicationDelegate method application:handleEventsForBackgroundURLSession:completionHandler: by the system.
application:handleEventsForBackgroundURLSession:completionHandler: is invoked (indirectly) by an external service process. When an application uses NSURLSession to create a background session, that session is managed by that system service. That service does the actual background transfer and notifies UIKit/Foundation and in turn your application through a mechanism called XPC. XPC is widely used by MacOS developers, but at this time is not directly available to iOS applications - however many of the APIs and services used by developers on iOS are actually communicating with XPC services.
In the case of application:handleEventsForBackgroundURLSession:completionHandler:, the block passed to the completionHandler parameter is an opaque callback. The background transfer service needs to know when your application is done handling events for the session. Invoking that block informs the service that the application has completely processing of this set of events and the daemon can move on.
The block is created and owned by the system and as such an application should not attempt to modify or change it (other than copying the block, which is the right thing to do!). Applications should also not provide their own completion blocks - a developer-provided block would have no way to inform the transfer service of completion unless it wrapped the block passed to completionHandler: itself.
The background transfer service and NSURLSession were introduced in iOS 7. If you are writing a third party framework or library it can be very beneficial to take advantage of the service, but the framework must provide a way to handle events for any background session it owns. Perhaps because of this only a few third party libraries seem to support background transfers. Supporting this is not difficult to do - the library only needs a method to indicate ownership of the session, and a method to take the completion block and handle the events:
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
if ([someCloudFrameworkObject canHandleEventsForSessionWithIdentifier:identifier]){
[someCloudFrameworkObject handleEventsForBackroundSessionWithIdentifier:identifier completionHandler:completionHandler];
}
}
I have an iPad app that uses a proprietary library object which registers for a "UIScreenDidConnectNotification". Occasionally this object is deallocated and reallocated behind the scenes. As it is in a library, I cannot ensure that it is properly removing this observer.
Is there a way for me to manually remove all/any observers for a specific notification (i.e. UIScreenDidConnectNotification) without having any access to the object that has registered. This would keep the application from sending the message to a deallocated object.
Update: Here is the easiest way to fix my problem. I wish I could do a better job, but life is too short.
#import
#import
#interface NSNotificationCenter (AllObservers)
#end
#implementation NSNotificationCenter (AllObservers)
// This function runs before main to swap in our special version of addObserver
+ (void) load
{
Method original, swizzled;
original = class_getInstanceMethod(self, #selector(addObserver:selector:name:object:));
swizzled = class_getInstanceMethod(self, #selector(swizzled_addObserver:selector:name:object:));
method_exchangeImplementations(original, swizzled);
// This function runs before main to swap in our special version of addObserver
+ (void) load
{
Method original, swizzled;
original = class_getInstanceMethod(self, #selector(addObserver:selector:name:object:));
swizzled = class_getInstanceMethod(self, #selector(swizzled_addObserver:selector:name:object:));
method_exchangeImplementations(original, swizzled);
}
/*
Use this function to remove any unwieldy behavior for adding observers
*/
- (void) swizzled_addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
{
NSString *notification = [[NSString alloc] initWithUTF8String: "UIScreenDidConnectNotification" ];
// It's a hack, but I just won't allow my app to add this type of notificiation
if([notificationName isEqualToString: notification])
{
printf("### screen notifcation added for an observer: %s\n", [notificationSender UTF8String] );
}
else
{
// Calls the original addObserver function
[self swizzled_addObserver:notificationObserver selector:notificationSelector name:notificationName object:notificationSender];
}
}
As it is in a library, I cannot ensure that it is properly removing this observer.
If the object is created in a library, it's not your responsibility to remove the object. If the library is deallocating the object without removing it from the notification center, that's a clear bug in the library.
Is there a way for me to manually remove all/any observers for a specific notification... without having any access to the object that has registered.
There's nothing in the API for NSNotificationCenter that lets you do that. Just the opposite, in fact -- the methods that let you remove the observer all require a pointer to a specific object.
I agree with both of Caleb's points: it is not your responsibility to perform this task and there is nothing in the API to support it.
However... if you feel like hacking something in to perform this task for whatever reason, refer to this thread: How to retrieve all NSNotificationCenter observers?
The selected answer of that thread has a category for NSNotificationCenter that allows you to retrieve all observers for a given notification name. Again, this is not recommended though.
I would like to log any NSNotifications posted by a single NSNotificationCenter shared accross my application. I have tried subclassing NSNotificationCenter with the intention of adding logging code to the three post methods, but it returns an instance of CFNotification center instead of my subclass.
Surely there is a way of monitoring NSNotification posting?
EDIT/UPDATE
As two answers below correctly point out I could listen to all notifications and log them in a handler, but the sequence the handler would receive these notifications is far from guaranteed to be the same as the sequence in which they were dispatched. If I could be sure the handler would always be the first hander to be notified this would work, but I cannot: 'The order in which observers receive notifications is undefined' From NSNotification Docs
By using - addObserver:selector:name:object: and passing nil for both the name and the object, you will get notified about any notification.
- (id)init
{
self = [super init];
if (self != nil)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(log:) name:nil object:nil];
}
return self;
}
- (void)log:(NSNotification *)notification
{
NSLog(#"%#", notification);
}
Edit: if you want to get the real order of the notifications being send, try subclassing NSNotificationCenter and overriding the following methods:
– postNotification:
– postNotificationName:object:
– postNotificationName:object:userInfo:
If subclassing is no option for you, you might consider defining a category on NSNotificationCenter where you override these methods with calling the super implementation. (you will need to swizzle methods to call super within a category). Tell me if you need help doing so.
You should be able to use [addObserver:self selector:#selector(whatever:) name:nil object:nil] and just put your logging code in the whatever: method. This observer should get all notifications posted by your app (at least all those posted by the default center).
Here are my objective-c classes:
AppDelegate
SomeScript
How might I call the function loggedIn on the SomeScript class from the app-delegate or any other class?
Thanks,
Christian Stewart
(I'll assume loggedIn is an instance method taking no parameters.) First, several terminology issues:
They're not functions, they're methods (same idea, though).
You don't call methods, you send messages (usually same idea, though).
Most importantly, we usually send messages not to classes, but to instances of those classes. (If you can't visualize the difference, imagine placing a letter in the idea of mailboxes vs. placing a letter in your mailbox. Only one makes sense!)
So, our new plan is to first instantiate SomeScript, then send a message to the instance.
SomeScript* myScript = [[SomeScript alloc] init]; //First, we create an instance of SomeScript
[myScript loggedIn]; //Next, we send the loggedIn message to our new instance
This is good. However! I bet you want your script to stick around for later use. Thus, we should really make it an instance variable of your app delegate. So, instead, in AppDelegate.h, add this inside the braces:
SomeScript* myScript;
Now our variable will stick around, and our first line from before becomes simply:
myScript = [[SomeScript alloc] init];
Last complication: we don't want to create a new script every time we call loggedIn (I assume)! So, you should place the instantiation somewhere it will only be run once (for example, application:DidFinishLaunchingWithOptions:). Ta-da!
You shall have an initialized reference of a SomeScript object in your AppDelegate class (supposing you do not need SomeScript to be a Singleton class like your AppDelegate). Something like:
SomeScript * myScript;
as an ivar in your AppDelegate interface, while in its application:DidFinishLaunchingWithOptions:
you have inited it (let's suppose with the default alloc/init combo calling):
myScript = [[SomeScript alloc] init]
Done all of this, when you need to call a method of myScript you can simply do:
[myScript myMethod:myParameter]
Here you can find a nice guide for beginners from Apple
If you don't want to use instances of SomeScript ... you can follow a different approach. Use NSNotificationCenter for sending a notification to your SomeScript object and make it run a selector after that.
In your -(void)awakeFromNib{} method, from SomeScript place the following code :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mySelector:)
name:#"aUniqueNameForTheNotification"
object:nil];
Create the method "mySelector:" and place the the call to your loggedIn method. (Or if you prefer, you could replace "mySelector:" with loggedIn directly)
-(void) mySelector:(id)elem
{
[self loggedIn];
}
Then don't forget to remove the observer on dealloc, so place the following piece of code in your SomeScript class also :
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Then you can send a notification from any other like so :
[[NSNotificationCenter defaultCenter] postNotificationName:#"aUniqueNameForTheNotification" object:self];
That last piece of code sends a notification to SomeScript and your selector is executed.
Hope it helps you guys!
We can call it like [self loggedIn] When loggedIn method is in SomeScript class, using simple syntaxes in latest xcode.
[[SomeScript new] loggedIn];
I am writing a program that displays to a console-like UITextView different events generated by my AudioSession and AudioQueues. For instance, when I detect that my audio route has changed, I just want a quickie message displayed on the screen on my iPhone that this happened. Unfortunately, I believe I am getting into some race condition nastiness, and I'm not sure what the best solution to solve this is.
When I run my program, my debug console spits this out:
bool _WebTryThreadLock(bool), 0x1349a0: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
This happens on a line of code:
textView.text = string;
I tried this:
[textView performSelectorOnMainThread:#selector(setText:) withObject:string waitForDone:YES];
And this seemed to have fixed it, but I'm pretty sure I shouldn't be doing something like this to get it to work. Unfortunately, this doesn't work with [UITextView scrollVisibleWithRange:] since this takes an NSRange, which isn't a descendant of NSObject. I think what I am doing is fundamentally wrong.
This code is called from an interruption listener, which runs from the audio queue's thread. Is there something that I should be doing that will make my updates to my textview blocking so I'm not getting this problem?
Thanks.
You are allowed to do anything about the view only from main thread, you did the right thing.
If it requires more parameters or primitive you may need a proxy function.
This is how I make a proxy function
// the caller should be like this
UTMainThreadOperationTextViewScroll *opr = [[UTMainThreadOperationTextViewScroll alloc] init];
opr.textView = textView;
opr.range = NSMakeRange(5, 10);
[UTMainThread performOperationInMainThread:opr];
[opr release];
// the Utility classes goes below
#interface UTMainThreadOperation : NSObject
- (void)executeOperation;
#end
#implementation UTMainThread
+ (void)performOperationInMainThread:(UTMainThreadOperation *)operaion
{
[operaion performSelectorOnMainThread:#selector(executeOperation) withObject:nil waitUntilDone:NO];
}
#end
#implementation UTMainThreadOperationTextViewScroll
#synthesize textView;
#synthesize range;
- (void)dealloc { /* I'm too lazy to post it here */ }
- (void)executeOperation
{
[textView scrollVisibleWithRange:range];
}
#end
PS. some declarations omitted