Passing Data through NSTimer UserInfo

后端 未结 6 2000
抹茶落季
抹茶落季 2021-01-31 09:18

I am trying to pass data through userInfo for an NSTimer call. What is the best way to do this? I am trying to use an NSDictionary, this is simple enough when I have Objective-C

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 10:11

    You have to wrap the information correctly into the dictionary:

    - (void) play:(SystemSoundID)sound target:(id)target callbackSelector:(SEL)selector
    {
        NSLog(@"pause ipod");
        [iPodController pause];
        theSound = sound;
    
        NSMutableDictionary *cb = [[NSMutableDictionary alloc] init];
        [cb setObject:[NSNumber numberWithInt:sound] forKey:@"sound"];
        [cb setObject:target forKey:@"target"];
        [cb setObject:NSStringFromSelector(selector) forKey:@"selector"];
    
        [NSTimer scheduledTimerWithTimeInterval:0
                                         target:self
                                       selector:@selector(notifyPause1:)
                                       userInfo:cb 
                                         repeats:NO];
        [cb release];
    
    }
    

    In notifyPause1:, you retrieve everything:

    - (void)notifyPause1:(NSTimer *)timer {
        NSDictionary *dict = [timer userInfo];
    
        SystemSoundID sound = [[dict objectForKey:@"sound"] intValue];
        id target = [dict objectForKey:@"target"];
        SEL selector = NSSelectorFromString([dict objectForKey:@"selector"]);
    
        // Do whatever...
    }
    

    As the timer is a repeating timer, you do not need the dictionary anymore, so you can release it.

提交回复
热议问题