我在這個難題(但對您而言很簡單)中遇到了兩天的問題。NSNotificationCenter無法在ViewControllers之間工作
的問題如下:
- 我張貼的通知中的appdelegate
- 我試圖獲得在視圖 - 控制該通知,但我不能接受它。
這是此代碼。
在appdelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSString * someString;
@end
在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;
}
的 「SomeContextExampleRef」 從.h文件來如下:
#ifndef SampleNotWorking_SomeContextExample_h
#define SampleNotWorking_SomeContextExample_h
#define SomeContextExampleRef @"SomeContextExampleRef"
#endif
最後,在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);
}];
}
我完整的代碼在這裏附: https://github.com/moomoo23/SampleNotWorking
感謝您幫助初學者!
你是快於我。在輸入相同的東西的過程中,將其刪除。 :D – Ricky
啊我看到了......這裏是我理解的差距:如果viewcontroller不存在於didfinishlaunchingwithoptions的末尾,則發佈的消息不在內存中?這意味着,一旦viewcontroller存在,它不能得到這個消息,因爲發佈的消息成爲零? – user330739
你在那裏做的發佈通知會被丟棄,因爲在啓動你的應用程序的最後還沒有觀察者。您必須將該「ViewController'」對象放入視圖(並實例化)才能讓觀察者觀察這些通知。 –