Cocoa对象空闲计时器

时间:2013-07-05 17:57:12

标签: objective-c cocoa

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

1 个答案:

答案 0 :(得分:0)

您可以使用委托模式。

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

2)JoystickController应该实现JoystickDelegate。实现从阵列中删除joystick的方法。

3)最后在delegate界面和JoystickJoystick的每个初始化joystickAdded上创建一个名为self的弱属性js.delegate invalidate }}。

4)现在每当调用delegate时,只需在self内使用Joystick拨打[self.delegate joystickInvalidated:self];

{{1}}