NSTimer代理选择



我正试图通过创建自定义委托类和自定义对象,为我经常制作和使用的所有自定义对象和视图创建一个框架。除了试图让NSTimer在委托类内部调用正确的方法之外,一切都很顺利。

这是基本设置。

-(void) startTimers {
    NSTimer *timer1 = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(doSomething:) userInfo:nil repeats:YES];
    NSTimer *timer2 = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(doSomethingElse:) userInfo:nil repeats:YES];
}

我可以很容易地调用这个方法等等,但当这次触发时,它不会调用我定义为选择器的方法。我确信这与委托值以及它作为委托生成的类有关。

请注意,我正在编写的文件是UIView的一个子类,它被设置为使用@protocol标记和所有这些的委托。

在定义计时器以使它们调用正确的方法时,我应该将什么设置为目标。

编辑:

下面是我正在做的一个例子:

示例View.h

#import <UIKit/UIKit.h>
@protocol ExampleViewDelegate;
@interface ExampleView : UIView {
    NSTimer *timer;
}
-(void) initWithStuff:(id)stuff andFrame:(CGRect)frame;
-(void) testTimer;
@end
@protocol ExampleViewDelegate
-(void) someDelegateFunction;
@end

示例View.m

#import "ExampleView.h"
@implementation ExampleView

-(id) initWithStuff:(id)stuff andFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(testTimer) userInfo:nil repeats:YES];
    return self;
}
-(void) testTimer {
    NSLog(@"Timer Fired");
}
@end

如果你把这个自定义视图添加到视图控制器中,它将永远不会调用testTimer函数并打印"Timer Fired"。所以我想的是,当我为这个计时器设置委托时,它实际上是在把它设置为其他东西。有什么想法吗?

NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(doSomething:) userInfo:nil repeats:YES];

请注意,该方法被称为"scheduledTimerWithTimeInterval"

最新更新