gpt4 book ai didi

ios - 从 AppDelegate 向 ViewController 发送通知

转载 作者:行者123 更新时间:2023-11-28 17:58:09 25 4
gpt4 key购买 nike

需要你的帮助。我将这些委托(delegate)方法实现到 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 或者我如何将这些委托(delegate)方法实现到 ViewController?

最佳答案

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

首先在您的应用委托(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];
}

希望对你有帮助。

关于ios - 从 AppDelegate 向 ViewController 发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16458078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com