从AppDelegate发送通知到ViewController

时间:2013-05-09 09:01:49

标签: ios objective-c

需要你的帮助。我将这些委托方法实现到AppDelegate.m:

    -(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中。我如何“发送”它们的URL或如何将这些委托方法实现到ViewController?

2 个答案:

答案 0 :(得分:12)

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

首先在您的app delegate中发布通知:

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];

然后将想要观察此通知的ViewController注册为

/***** 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];
}

然后在UnLoad上通过调用此方法删除此观察者:

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


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

希望它对你有所帮助。

答案 1 :(得分:6)

您可以发布此类本地通知,其中通知名称将由接收方用于订阅。

[[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

的更多信息