0

需要你的帮助。我将这些委托方法实现到 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;

但是现在,我需要的不是 AppDelegate 中的 URL,而是我的 ViewController 中的 URL。我如何向他们“发送” url 或如何将这些委托方法实现到 ViewController?

4

2 回答 2

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

然后注册你想要观察这个通知的 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];
}

希望它可以帮助你。

于 2013-05-09T09:15:43.673 回答
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 的更多信息,可以使用此链接

于 2013-05-09T09:07:35.167 回答