【问题标题】:NSTimer Delegate SelectionNSTimer 代表选择
【发布时间】:2012-02-15 06:38:55
【问题描述】:

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

这是基本设置。

-(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 标记和所有这些的委托。

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

编辑:

这是我正在做的一个例子:

ExampleView.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

ExampleView.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”所以​​我的想法是,当我为这个计时器设置委托时,它实际上是将其设置为其他东西。有什么想法吗?

【问题讨论】:

  • 您是在 UIView 或 UIViewController 的子类中定义 startTimers 吗?
  • 定时器没有代表;你在说什么协议?我猜你的方法名称和你传递的选择器之间有错字。你遇到车祸了吗?
  • 修改已提交,请查看。

标签: iphone ios ios5 delegates nstimer


【解决方案1】:
NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(doSomething:) userInfo:nil repeats:YES];

注意这个方法叫做“scheduledTimerWithTimeInterval”

【讨论】:

  • 很好看。这确实是问题所在。 timerWithTimeInterval:... 是一个有效的方法,但不会像scheduledTimer... 那样将计时器添加到运行循环中,这意味着计时器已创建但不执行任何操作。
  • 哇,我现在简直不能再傻了。维尼的好地方。我以前使用过很多次 NSTimers,并且让它们工作,但由于某种原因,这次我定义不正确。我想这就是你在凌晨 2 点编程所得到的 :)。非常感谢!
  • 我之所以知道,是因为几个月前我有过完全相同的浪费时间的经历。你们相处得很好。
猜你喜欢
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多