当在FirstVC
点击按钮时,它会传递数据并使用NSNotificationCenter触发SecondVC
在应用初始启动时,由于SecondVC
还没有初始化,所以数据无法传递给SecondVC
。 NSNotificationCenter
无法正常运行。只有在 SecondVC
初始化后,NSNotificationCenter
才能正常运行。
所以我需要在某处初始化SecondVC
。它会在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
处吗?
或者我如何以编程方式调用 SecondVC
的选项卡。
第一风投
#import "Search.h"
#import "Classes.h"
#import "MyTabBarController.h"
@interface Search(){
AppDelegate *appDelegate;
CERangeSlider* _rangeSlider;
NSString *sURL, *strResult, *sRemaining, *sStartTime, *sEndTime, *sSelectedLat, *sSelectedLong;
}
@end
@implementation Search
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)btnSearch:(UIButton *)sender {
self.tabBarController.selectedIndex = 1;
sURL = @"Testing 123";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:sURL forKey:@"theURL"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"toClasses" object:nil userInfo:userInfo];
}
@end
第二个VC
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(receiveTestNotification:)
name:@"toClasses"
object:nil];
dtDate = [[NSMutableArray alloc] init]; //=== Mutable array to store the dates generated
self.currentPageIndex = 0;
[self setupSegmentButtons];
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/YYYY"];
sDtDate = [dateFormatter stringFromDate:now];
[self LoadClasses];
}
-(void)viewWillAppear:(BOOL)animated {
//--- Hide the Top Navigation Controller Bar at the current View
[[self navigationController] setNavigationBarHidden:YES animated:YES];
}
//--- Top Navigation Controller reappear on the next VC
-(void)viewDidDisappear:(BOOL)animated{
[[self navigationController] setNavigationBarHidden:NO animated:YES];
}
-(void) receiveTestNotification:(NSNotification*)notification
{
if ([notification.name isEqualToString:@"toClasses"])
{
NSDictionary* userInfo = notification.userInfo;
NSLog (@"Successfully received userInfo! %@", userInfo);
NSString* sFromSearch = [NSString stringWithFormat: @"%@", userInfo];
NSLog (@"Successfully received test notification! %@", sFromSearch);
}
}
最佳答案
在我看来,您不需要在这种情况下使用通知或单例。
简单地说,从self.tabBarController
获取SecondViewController
并调用方法。
第一位风投
- (IBAction)btnSearch:(UIButton *)sender {
self.tabBarController.selectedIndex = 1;
sURL = @"Testing 123";
UINavigationController* secondNav = (UINavigationController*)self.tabBarController.viewControllers[1];
SecondViewController* secondViewController = [secondNav.viewControllers firstObject];
[secondViewController handleString:sURL];
}
第二个VC
- (void)handleString:(NSString*)string {
// Do whatever you want with string passed from First VC
}
关于ios - 如何初始化 VC 或 Class iOS, Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895142/