从AppDelegate发送通知给ViewController
需要你的帮助。 我将这些委托方法实现到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?
您可以使用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]; }
希望它可以帮助你。
可以这样做发送通知给所有用户。
[[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的更多信息可以使用此链接