2013-05-09 74 views
-1

需要您的幫助。我實現這些委託方法的AppDelegate.m:發送從AppDelegate到ViewController的通知

-(BOOL)application:(UIApplication *)application 
      openURL:(NSURL *)url 
sourceApplication:(NSString *)sourceApplication 
     annotation:(id)annotation { 
    if (url != nil && [url isFileURL]) { 
     //Valid URL, send a message to the view controller with the url 
    } 
    else { 
     //No valid url 
    } 
    return YES; 

但現在,我需要的URL不是在AppDelegate的,但在我的ViewController。我怎樣才能「發送」他們的網址,或者我如何將這些委託方法實現到ViewController?

回答

12

您可以使用NSNotificationCenter,如下圖所示:

首先,在您的應用程序代理後通知如下:

NSDictionary *_dictionary=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%d",newIndex],nil] forKeys:[NSArray arrayWithObjects:SELECTED_INDEX,nil]]; 

[[NSNotificationCenter defaultCenter] postNotificationName:SELECT_INDEX_NOTIFICATION object:nil userInfo:_dictionary]; 

然後註冊您需要的視圖控制器觀察此通知爲

/***** To register and unregister for notification on recieving messages *****/ 
- (void)registerForNotifications 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(yourCustomMethod:) 
               name:SELECT_INDEX_NOTIFICATION object:nil]; 
} 

/*** Your custom method called on notification ***/ 
-(void)yourCustomMethod:(NSNotification*)_notification 
{ 
    [[self navigationController] popToRootViewControllerAnimated:YES]; 
    NSString *selectedIndex=[[_notification userInfo] objectForKey:SELECTED_INDEX]; 
    NSLog(@"selectedIndex : %@",selectedIndex); 

} 

調用此方法viewDidLoad中爲:

- (void)viewDidLoad 
{ 

    [self registerForNotifications]; 
} 

,然後卸載通過調用此方法刪除此觀察:

-(void)unregisterForNotifications 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SELECT_INDEX_NOTIFICATION object:nil]; 
} 


-(void)viewDidUnload 
{ 
    [self unregisterForNotifications]; 
} 

希望它可以幫助你。

5

您可以發佈像這樣的本地通知,其中通知名稱將由接收方用於訂閱。

[[NSNotificationCenter defaultCenter] 
    postNotificationName:@"Data" 
    object:nil]; 

並在您的viewController訂閱通知。

[[NSNotificationCenter defaultCenter] 
    addObserver:self 
    selector:@selector(getData:) 
    notificationName:@"Data" 
    object:nil]; 

- getData:(NSNotification *)notification { 
    NSString *tappedIndex = [[_notification userInfo] objectForKey:@"KEY"]; 
} 

瞭解更多關於NSNotificationCenter Can go with this link

+0

您好,其中i必須把這個代碼:[[NSNotificationCenter defaultCenter] 的addObserver:自 選擇器:@selector(:)的getData notificationName:@ 「數據」 對象:yourdata]; – Marv 2013-05-09 09:13:37

+0

你想檢查通知數據,你可以把它叫做viewDidLoad – Buntylm 2013-05-09 09:21:39

+0

我們如何才能將你的數據作爲viewController中的對象? – 2015-02-25 07:11:43

相關問題