我正在尝试在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
}
设置调用并运行NSOperationQueue似乎没问题,并且使用正确的参数调用apiCallbackQueueTimer方法。问题是我无法运行NSTimer,因此转到我的apiCallbackMonitor方法。
我在文档中读到NSTimer需要一个运行循环,所以我一直试图添加一个。
谁能看到我做错了什么?
答案 0 :(得分:7)
事实证明我只需要启动runloop。
更改apiCallbackQueueTimer的最后几行解决了这个问题。
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:apiTimer forMode:NSRunLoopCommonModes];
[runLoop run];
答案 1 :(得分:2)
创建NSInvocationOperation时,没有实例化运行循环。操作开始时可能会发生这种情况。
Soooo,我建议继承NSInvocationOperation,并在调用子类[NSInvocationOperation start]方法时调用apiCallbackQueueTimer选择器。