我在SecondViewController.m文件中有一些函数,我想在启动应用程序时调用这些函数。我试过这样做,但它不起作用。
我在函数中放了一个print语句,看它是否被调用,看起来print语句正确执行。
以下是代码:
在SecondViewController.h中:
@interface AlertsManagementController : UIViewController {
PushNotificationSettings *pushNotificationSettings;
IBOutlet UISwitch *switch1;
IBOutlet UISwitch *switch2;
}
@property (nonatomic, retain) PushNotificationSettings *pushNotificationSettings;
在SecondViewController.m中:
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (projectAppDelegate *)[[UIApplication sharedApplication] delegate];
pushNotificationSettings = [[PushNotificationSettings alloc] init];
NSDictionary * settings = [pushNotificationSettings getPushSettings];
}
-(void)modificationPush
{
if (switch1.on && switch2.on)
[switch2 setOn:NO];
printf("Function 1 executed!");
}
-(void)sendTokenFunc{
NSMutableDictionary *preferences1 = [[NSMutableDictionary alloc] init];
if (switch1.on)
[preferences1 setObject:@"1" forKey:@“switch1”];
else
[preferences1 setObject:@"0" forKey:@“switch1”];
if (switch2.on)
[preferences1 setObject:@"1" forKey:@“switch2”];
else
[preferences1 setObject:@"0" forKey:@“switch2”];
[pushNotificationSettings savePushSettingsWithDictionary:preferences1];
[preferences1 release];
[appDelegate uploadToken:[appDelegate tokenValue]];
printf("Function 2 executed!");
}
在appDelegate.m中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
SecondViewController * vc = [[SecondViewController alloc]init];
[vc modificationPuch];
[vc sendTokenFunc];
}
答案 0 :(得分:1)
这可以通过使用NSNotificationCenter来完成。
首先转到SecondViewController.m文件,然后在viewDidLoad中编写以下代码。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotification:) name:@"myNotification" object:nil];
然后在viewDidLoad之外创建一个函数myNotification。我会告诉你例如下面的
- (无效)myNotification:(NSNotification *)通知 {
//在应用程序打开时编写您想要执行的代码
}
转到appDeligate.m并在应用程序中编写此代码didFinishLaunchingWithOptions
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self userInfo:nil];
谢谢你, 快乐的编码;)
答案 1 :(得分:0)
但是如果SecondViewController没有,你必须得到EXC_BAD_ACCESS:)