在NSOperationQueue线程中运行NSTimer

Phi*_*ohn 3 nstimer nsoperationqueue ios

我正在尝试在NSOperationQueue设置的线程上运行NSTimer

-(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
 }
Run Code Online (Sandbox Code Playgroud)

设置调用并运行NSOperationQueue似乎没问题,并且使用正确的参数调用apiCallbackQueueTimer方法.问题是我无法运行NSTimer,所以进入我的apiCallbackMonitor方法.

我在文档中读到NSTimer需要一个运行循环,所以我一直在尝试添加一个.

谁能看到我做错了什么?

Phi*_*ohn 7

事实证明,我只需要启动runloop.

更改apiCallbackQueueTimer的最后几行解决了这个问题.

 NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:apiTimer forMode:NSRunLoopCommonModes];
[runLoop run];
Run Code Online (Sandbox Code Playgroud)