当我的应用程序关闭时,我希望它调用 void 方法viewController.m
我试过这个:
我已经在viewController.h
中申报了NSTimer
(警报(和void(alarm:)
,并在Appdelegate.m
中导入了viewController.h
AppDelegate.m:
- (void)applicationDidEnterBackground:(UIApplication *)application{
alarmm = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(alarm:) userInfo:nil repeats:YES];
}
但是当它运行时,这就来了
**2014-12-20 13:53:19.881 protect my phone[3292:959295] -[AppDelegate alarm:]: unrecognized selector sent to instance 0x170043810
2014-12-20 13:53:19.884 protect my phone[3292:959295] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppDelegate alarm:]: unrecognized selector sent to instance 0x170043810'
*** First throw call stack:
(0x182e5659c 0x1935600e4 0x182e5d664 0x182e5a418 0x182d5eb6c 0x183d2ae18 0x182e0e8d8 0x182e0e588 0x182e0bfd4 0x182d390a4 0x18bee35a4 0x18766e3c0 0x10000a320 0x193bcea08)
libc++abi.dylib: terminating with uncaught exception of type NSException**
你所说,你在某些视图控制器中声明了alarm
,但你尝试在未定义AppDelegate
上调用它。因此,您会遇到无法识别的选择器的崩溃。
尝试将创建NSTimer
中的自我交换到视图控制器参考...
正如 dogsgod 已经说过的,您将目标设置为 self
,这是AppDelegate
。因此,您的计划计时器将在 AppDelegate 中查找此方法,但您在视图控制器中实现了 alarm 方法。您必须获取对视图控制器的引用,并将此引用设置为计时器的目标。
不需要AppDelegate
中的任何重要内容,您还可以在视图控制器中注册通知UIApplicationDidEnterBackgroundNotification
并在通知回调中创建计时器。
在您的视图控制器中列出了以下内容:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
- (void)onAppDidEnterBackground:(NSNotification *)notification {
NSTimer *alarmm = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(alarm:) userInfo:nil repeats:YES];
}