2014-05-10 25 views
0

我在這個難題(但對您而言很簡單)中遇到了兩天的問題。NSNotificationCenter無法在ViewControllers之間工作

的問題如下:

  1. 我張貼的通知中的appdelegate
  2. 我試圖獲得在視圖 - 控制該通知,但我不能接受它。

這是此代碼。

在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

感謝您幫助初學者!

回答

3

嘗試發佈您的通知,當你確信你的「ViewController」對象已經實例化和/或進入視野。例如。爲什麼不嘗試將它放入由某個UIButton觸發的「IBAction」方法?

觀察視圖控制器可能會(也可能不會)在您的應用程序委託中存在於「application:didFinishLaunchingWithOptions:」末尾。

+0

你是快於我。在輸入相同的東西的過程中,將其刪除。 :D – Ricky

+0

啊我看到了......這裏是我理解的差距:如果viewcontroller不存在於didfinishlaunchingwithoptions的末尾,則發佈的消息不在內存中?這意味着,一旦viewcontroller存在,它不能得到這個消息,因爲發佈的消息成爲零? – user330739

+0

你在那裏做的發佈通知會被丟棄,因爲在啓動你的應用程序的最後還沒有觀察者。您必須將該「ViewController'」對象放入視圖(並實例化)才能讓觀察者觀察這些通知。 –

0

另一種替代方法是使用scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:方法在延遲後發佈通知。

現在,在概念上,你爲什麼會發布通知時,appFinsihedLaunching?....只是好奇....è

+0

感謝您的建議。在高層次上,我從服務器提取數據,並使用coredata存儲它。但我需要一種方式告知我的觀點,即獲取已完成..因此通知。另一個可能的解釋是,我不知道我在做什麼=) – user330739

+1

@ user330739。這就說得通了。但不是在appDidFinishLoadingWithOptions方法中發佈通知,而是在後臺的不同線程中啓動數據獲取和CoreData處理,這將爲視圖控制器實例化並提供足夠的時間來準備好接收通知。 – eharo2

相關問題