iphone - 通过 NSTimer UserInfo 传递数据

标签 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];
}

最佳答案

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

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

}

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...
}

由于定时器是一个重复定时器,你不再需要字典了,所以你可以释放它。

关于iphone - 通过 NSTimer UserInfo 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2651882/

相关文章:

iphone - 获取 iPhone 连接的路由器的 IP 地址

ios - Swift-获取自计时器启动以来经过了多少秒/毫秒

iphone - 形状的缩放和旋转(矩形)

iphone - Objective-C 正确复制 NSArray?

iphone - NSURL URLWithString : raises exception

ios - 无法使用 Storyboard执行 segue back

objective-c - 检查是否有代表在听?

iPhone Web 服务通过证书身份验证调用 WCF 服务

ios - 可以在iOS应用中使AlertView超时吗?

objective-c - NSTimer 和 NSRunLoop