簡體   English   中英

如何從我的應用程序委托啟動NSTimer,該委托在Viewcontroller.m中調用我的方法

[英]How do I start an NSTimer from my app delegate which calls my method in Viewcontroller.m

當我的應用關閉時,我希望它在viewController.m調用void方法

我嘗試了這個:

我已經宣布NSTimer (alarmm)和void(alarm:)viewController.h我已經進口viewController.hAppdelegate.m

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創建中的self交換為視圖控制器參考...

正如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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM