我想了解根據指定的空閒時間使對象失效的最佳方法。我有一個操縱桿對象,從下面的joystickAdded方法實例化時,會自動啓動一個NSTimer爲該實例:可可對象空閒計時器
操縱桿
idleTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(invalidate) userInfo:nil repeats:YES];
這工作得很好,但我的操縱桿陣列犯規得到清理,因爲該方法當閒置時應該調用joystickRemoved,但我不知道如何調用它,或者如果NSTimer是最佳方式。
JoystickController
void joystickAdded(void *inContext, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
JoystickController *self = (__bridge JoystickController*)inContext;
IOHIDDeviceOpen(device, kIOHIDOptionsTypeNone);
// Filter events for joystickAction
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:kIOHIDElementTypeInput_Button] forKey:(NSString*)CFSTR(kIOHIDElementTypeKey)];
IOHIDDeviceSetInputValueMatching(device, (__bridge CFDictionaryRef)(dict));
// Register callback for action event to find the joystick easier
IOHIDDeviceRegisterInputValueCallback(device, joystickAction, (__bridge void*)self);
Joystick *js = [[Joystick alloc] initWithDevice:device];
[[self joysticks] addObject:js];
}
void joystickRemoved(void *inContext, IOReturn inResult, void *inSender, IOHIDDeviceRef device) {
// Find joystick
JoystickController *self = (__bridge JoystickController*)inContext;
Joystick *js = [self findJoystickByRef:device];
if(!js) {
NSLog(@"Warning: No joysticks to remove");
return;
}
[[self joysticks] removeObject:js];
[js invalidate];
}
void joystickAction(void *inContext, IOReturn inResult, void *inSender, IOHIDValueRef value) {
long buttonState;
// Find joystick
JoystickController *self = (__bridge JoystickController*)inContext;
IOHIDDeviceRef device = IOHIDQueueGetDevice((IOHIDQueueRef) inSender);
Joystick *js = [self findJoystickByRef:device];
// Get button state
buttonState = IOHIDValueGetIntegerValue(value);
switch (buttonState) {
// Button pressed
case 1: {
// Reset joystick idle timer
[[js idleTimer] setFireDate:[NSDate dateWithTimeIntervalSinceNow:300]];
break;
}
// Button released
case 0:
break;
}
}
的'NSTimer'將調用'invalidate'你的'JoystickController'。那個方法在哪裏? – Danilo
'invalidate'在Joystick類中,因此,'[js invalidate]' – nmajin
啊定時器在'操縱桿'而不是控制器,我的壞。 – Danilo