Возможно, будет немного поздно опубликовать второй ответ на этот вопрос, но я искал подходящее место, чтобы опубликовать собственное решение этой проблемы. На случай, если это кому-нибудь пригодится, вот оно. Он срабатывает 8 раз, но, конечно, его можно настроить по своему усмотрению. Таймер освобождает себя, когда время истекло.
Мне нравится этот подход, потому что он сохраняет счетчик интегрированным с таймером.
Чтобы создать экземпляр, вызовите что-то вроде:
SpecialKTimer *timer = [[SpecialKTimer alloc] initWithTimeInterval:0.1
andTarget:myObject
andSelector:@selector(methodInMyObjectForTimer)];
В любом случае, вот заголовок и файлы методов.
//Header
#import <Foundation/Foundation.h>
@interface SpecialKTimer : NSObject {
@private
NSTimer *timer;
id target;
SEL selector;
unsigned int counter;
}
- (id)initWithTimeInterval:(NSTimeInterval)seconds
andTarget:(id)t
andSelector:(SEL)s;
- (void)dealloc;
@end
//Implementation
#import "SpecialKTimer.h"
@interface SpecialKTimer()
- (void)resetCounter;
- (void)incrementCounter;
- (void)targetMethod;
@end
@implementation SpecialKTimer
- (id)initWithTimeInterval:(NSTimeInterval)seconds
andTarget:(id)t
andSelector:(SEL)s {
if ( self == [super init] ) {
[self resetCounter];
target = t;
selector = s;
timer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(targetMethod)
userInfo:nil
repeats:YES];
}
return self;
}
- (void)resetCounter {
counter = 0;
}
- (void)incrementCounter {
counter++;
}
- (void)targetMethod {
if ( counter < 8 ) {
IMP methodPointer = [target methodForSelector:selector];
methodPointer(target, selector);
[self incrementCounter];
}
else {
[timer invalidate];
[self release];
}
}
- (void)dealloc {
[super dealloc];
}
@end