2

我试图了解根据指定的空闲时间使对象无效的最佳方法。我有一个游戏杆对象,当从下面的 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;
    }
}
4

1 回答 1

0

您可以使用委托模式。

1)制定协议JoystickDelegate,声明方法- (void)joystickInvalidated:(Joystick *)joystick

2)JoystickController然后应该实施JoystickDelegate。实现joystick从数组中删除的方法。

delegate3)最后在接口中调用一个弱属性,并在分配上Joystick的每个初始化上调用。JoystickjoystickAddedselfjs.delegate

4)现在无论何时invalidate调用,只需调用delegatewith selfinside Joystick

[self.delegate joystickInvalidated:self];
于 2013-07-05T20:39:01.243 回答