gpt4 book ai didi

objective-c - NSTimer 在触发时导致 "unrecognized selector"崩溃

转载 作者:可可西里 更新时间:2023-11-01 06:19:19 24 4
gpt4 key购买 nike

我正在使用 NSTimer 来运行动画(现在只称它为 myMethod)。但是,它会导致崩溃。

代码如下:

@implementation SecondViewController


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.


- (void) myMethod
{
NSLog(@"Mark Timer Fire");

}


- (void)viewDidLoad
{
[super viewDidLoad];



NSLog(@"We've loaded scan");

[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(myMethod:)
userInfo:nil
repeats:YES];

animationTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(myMethod:) userInfo:nil repeats: YES];


}

这是崩溃期间的输出

-[SecondViewController myMethod:]: unrecognized selector sent to instance 0x4b2ca40 2012-06-21 12:19:53.297 Lie Detector[38912:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SecondViewController myMethod:]: unrecognized selector sent to instance 0x4b2ca40'

那么我做错了什么?

最佳答案

我在使用 Swift 时遇到了这个问题。可能不是很明显,在 Swift 中我发现 NSTimer 的目标对象必须是 NSObject。

class Timer : NSObject {
init () { super.init() }
func schedule() {
NSTimer.scheduledTimerWithTimeInterval(2.0,
target: self,
selector: "myMethod",
userInfo: nil,
repeats: true)
}
func myMethod() {
...
}
}

希望这对某人有帮助。

关于objective-c - NSTimer 在触发时导致 "unrecognized selector"崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11145333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com