我试图了解根据指定的空闲时间使对象无效的最佳方法。我有一个游戏杆对象,当从下面的 joystickAdded 方法实例化时,会自动为该实例启动一个 NSTimer:
操纵杆
idleTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(invalidate) userInfo:nil repeats:YES];
这工作正常,但我的游戏杆数组没有得到清理,因为空闲时应该调用的方法是 joystickRemoved,但我不知道如何调用它,或者 NSTimer 是否是最好的方法。
操纵杆控制器
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;
}
}