Frage

Ive been hitting the wall for two days on this hard (but simple for you) problem.

The problem is as follows:

  1. I am posting a notification in the appdelegate
  2. I am attempting to receive that notification in a viewcontroller but I cannot receive it.

Here is the code for this.

In the appdelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSString * someString;
@end

In the appdelegate.m

#import "AppDelegate.h"
#import "SomeContextExample.h"


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.

    self.someString = @"Hello!";


    NSDictionary * userInfo = @{SomeContextExampleRef : self.someString};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SomeContextExample"
                                                        object:nil
                                                      userInfo:userInfo];

return YES;
}

The "SomeContextExampleRef" is coming from a .h file as follows:

#ifndef SampleNotWorking_SomeContextExample_h
#define SampleNotWorking_SomeContextExample_h

#define SomeContextExampleRef @"SomeContextExampleRef"

#endif

Finally, in the viewController.m:

#import "ViewController.h"
#import "SomeContextExample.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:@"SomeContextExample"
                                                  object:nil
                                                   queue:mainQueue
                                              usingBlock:^(NSNotification *note)
 {

     NSLog(@"got the notification!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! %@", note.userInfo);



 }];
}

My full code is attached here: https://github.com/moomoo23/SampleNotWorking

Thank you for helping a beginner!

War es hilfreich?

Lösung

Try posting your notification when you are confident your "ViewController" object has instantiated and/or come into view. E.G. why not try it out by putting it into an "IBAction" method fired by some UIButton?

The observing view controller may or may not (more likely not in your case) be existing at the end of "application:didFinishLaunchingWithOptions:" in your app delegate.

Andere Tipps

Another alternative is to post the notification after a delay using the scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: method.

Now, conceptually, why would you post a notification when the appFinsihedLaunching?.... just curious.... e

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top