通过NSTimer UserInfo传递数据

zor*_*o2b 27 iphone objective-c nstimer

我正在尝试通过userInfo传递数据以进行NSTimer调用.做这个的最好方式是什么?我正在尝试使用NSDictionary,当我有Objective-C对象时,这很简单,但其他数据呢?我想做这样的事情,它不能正常工作:

- (void)play:(SystemSoundID)sound target:(id)target callbackSelector:(SEL)selector
{
    NSLog(@"pause ipod");
    [iPodController pause];
    theSound = sound;

    NSMutableDictionary *cb = [[NSMutableDictionary alloc] init];
    [cb setObject:(id)&sound forKey:@"sound"];
    [cb setObject:target forKey:@"target"];
    [cb setObject:(id)&selector forKey:@"selector"];

    [NSTimer scheduledTimerWithTimeInterval:0
                                     target:self
                                   selector:@selector(notifyPause1:)
                                   userInfo:(id)cb
                                    repeats:NO];
}
Run Code Online (Sandbox Code Playgroud)

Lau*_*ble 49

您必须将信息正确地包装到字典中:

- (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];

}
Run Code Online (Sandbox Code Playgroud)

notifyPause1:,您检索所有内容:

- (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...
}
Run Code Online (Sandbox Code Playgroud)

由于计时器是重复计时器,您不再需要字典,因此您可以释放它.


sch*_*ele 7

您的通话是正确的,但您不必将字典转换为id.您可以使用notifyPause1:方法中的以下行返回userInfo:

- (void)notifyPause1:(NSTimer *)timer {

    NSDictionary *dict = [timer userInfo];

}
Run Code Online (Sandbox Code Playgroud)


avi*_*hic 6

你可以在给选择器的方法中要求定时器,

然后你可以从那个计时器(timer.userInfo)中获取useInfo :

- (void)settingTimer
{
[NSTimer scheduledTimerWithTimeInterval:kYourTimeInterval
                                 target:self
                               selector:@selector(timerFired:)
                               userInfo:yourObject
                                repeats:NO];
}

- (void)timerFired:(NSTimer*)theTimer
{
  id yourObject = theTimer.userInfo;
  //your code here
}
Run Code Online (Sandbox Code Playgroud)