Objective c 目标C&;iOS:运行计时器?NSTimer/Threads/NSDate/etc
我正在开发我的第一个iOS应用程序,遇到了第一个无法找到好答案的障碍 问题是:我有一个自定义的Objective c 目标C&;iOS:运行计时器?NSTimer/Threads/NSDate/etc,objective-c,ios,nsdate,nstimer,nsthread,Objective C,Ios,Nsdate,Nstimer,Nsthread,我正在开发我的第一个iOS应用程序,遇到了第一个无法找到好答案的障碍 问题是:我有一个自定义的uigesturecognizer,并将其正确连接,识别后我可以在@选择器中为每次触摸运行代码。这对大多数事情来说都很好,但对其他人来说有点太多了 我的目标是:制作一个以指定间隔触发的计时器来运行逻辑,并能够在触摸被取消时取消此操作 我为什么在这里发问:有很多解决方案的可能性,但没有一个是最适合实施的。目前看来 performSelector(以及在此基础上的一些变体) NSThread NSTime
uigesturecognizer
,并将其正确连接,识别后我可以在@选择器中为每次触摸运行代码。这对大多数事情来说都很好,但对其他人来说有点太多了
我的目标是:制作一个以指定间隔触发的计时器来运行逻辑,并能够在触摸被取消时取消此操作
我为什么在这里发问:有很多解决方案的可能性,但没有一个是最适合实施的。目前看来
performSelector
(以及在此基础上的一些变体)
NSThread
NSTimer
NSDate
- 操作队列
- 我想我也找到了一些其他的
从所有的研究来看,某种形式的线程似乎是一条可行的路线,但我不知道在这种情况下哪种方式最有效
实现示例:每0.10秒获取一个NSPoint
,并获取上一个点和当前点之间的距离。[测量每个点之间的距离会产生非常混乱的结果]
有关守则:
- (void)viewDidLoad {
CUIVerticalSwipeHold *vSwipe =
[[CUIVerticalSwipeHold alloc]
initWithTarget:self
action:@selector(touchHoldMove:)];
[self.view addGestureRecognizer:vSwipe];
[vSwipe requireGestureRecognizerToFail:doubleTap];
}
...
- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
}
if (sender.state == UIGestureRecognizerStateBegan) {
}
//other stuff to do goes here
}
使用NSTimer
设置如下:
theTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(yourMethodThatYouWantRunEachTimeTheTimerFires) userInfo:nil repeats:YES];
然后,如果要取消,请执行以下操作:
if ([theTimer isValid])
{
[theTimer invalidate];
}
请注意,在上面的示例中,您需要声明NSTimer的“theTimer”实例,在该实例中,这两种方法都可以使用它。在上述示例中,“0.5”表示计时器每秒将触发两次。根据需要进行调整。为了完整性起见,我在这里添加了我的最终实现(不确定这是实现的方法,但现在开始)
H
M
注:在计时器失效后将其设置为零被认为是良好的做法:[计时器失效];时间=零;
@interface {
NSTimer *myTimer;
}
@property (nonatomic, retain) NSTimer *myTimer;
@synthesize myTimer;
-------------------------------------------
- (void)viewDidLoad {
//Relevant snipet
CUIVerticalSwipeHold *vSwipe =
[[CUIVerticalSwipeHold alloc]
initWithTarget:self
action:@selector(touchHoldMove:)];
[self.view addGestureRecognizer:vSwipe];
[vSwipe requireGestureRecognizerToFail:doubleTap];
}
-------------------------------------------
- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
//Cancel the timer when the gesture ends
if ([myTimer isValid])
{
[myTimer invalidate];
}
}
}
if (sender.state == UIGestureRecognizerStateBegan) {
//starting the timer when the gesture begins
myTimer = [NSTimer scheduledTimerWithTimeInterval:someTimeIncrement
target:self
selector:@selector(someSelector)
userInfo:nil
repeats:YES];
}
}