Запуск NSTimer в потоке NSOperationQueue - PullRequest
3 голосов
/ 10 октября 2011

Я пытаюсь запустить NSTimer в потоке, настроенном с помощью NSOperationQueue

-(void)apiCallbackQueueManager:(NSString *)callid :(NSString *)service:(NSString *)action:(NSString *)data{

SEL theSelector = @selector(apiCallbackQueueTimer: service: action: data:);
NSMethodSignature * sig = [self methodSignatureForSelector:theSelector];
NSInvocation * theInvocation = [NSInvocation invocationWithMethodSignature:sig];
[theInvocation setTarget: self];
[theInvocation setSelector: theSelector];
[theInvocation setArgument: &callid atIndex: 2];
[theInvocation setArgument: &service atIndex: 3];
[theInvocation setArgument: &action atIndex: 4];
[theInvocation setArgument: &data atIndex: 5];

NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithInvocation:theInvocation];
NSOperationQueue *apiQueue = [[NSOperationQueue alloc] init];
[apiQueue addOperation:operation];
 }

-(void)apiCallbackQueueTimer:(NSString *)arg1 service:(NSString *)arg2 action:(NSString *)arg3 data:(NSString *)arg4{
apiTimer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(apiCallbackMonitor:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:arg1, @"callid", arg2, @"service", arg3, @"action", arg4, @"data", nil] repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:apiTimer forMode:NSDefaultRunLoopMode];
 }

-(void)apiCallbackMonitor:(NSTimer *)theTimer{
//do something
 }

Настройка вызова и запуск NSOperationQueue вроде бы в порядке, и метод apiCallbackQueueTimer вызывается с правильными аргументами,Проблема в том, что я не могу запустить NSTimer и, таким образом, получить доступ к моему методу apiCallbackMonitor.

В документах я прочитал, что NSTimer требуется цикл выполнения, поэтому я пытался добавить его.

Кто-нибудь может увидеть, что я делаю не так?

Ответы [ 2 ]

7 голосов
/ 11 октября 2011

Оказывается, мне просто нужно было запустить runloop.

Изменение последних нескольких строк apiCallbackQueueTimer решило проблему.

 NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:apiTimer forMode:NSRunLoopCommonModes];
[runLoop run];
2 голосов
/ 10 октября 2011

При создании этой NSInvocationOperation не создается экземпляр цикла выполнения. Это, вероятно, происходит, когда начинается операция.

Ооо, я бы предложил создать подкласс NSInvocationOperation и чтобы этот селектор apiCallbackQueueTimer вызывался при вызове вашего метода подкласса [NSInvocationOperation start].

...