0

我想在一段时间后从 NSMutableDictionary 中删除一些对象。

我有:

//first Method start
    PedObjectTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(fireTimer:) userInfo:PedMessage repeats:YES];
    [PedMessage setObject:PedObjectTimer forKey:@"Timer"];
    [PedObjects setObject:[PedMessage copy] forKey:[PedMessage objectForKey:@"ObjectID"]];
//first Method end



- (void) fireTimer:(NSTimer*)theTimer {

    NSLog(@"%@",PedObjects);
    [PedObjects removeObjectForKey:[[theTimer userInfo]objectForKey:@"ObjectID"]];
    NSLog(@"%@",PedObjects);

    [theTimer invalidate];
    theTimer = nil;
}

一个问题是我无法将计时器对象复制到字典中......

如何在 fireTimer 方法中 2 秒后删除正确的?

有了这个我得到相同的结果,如果我有 2 个选择器,它不会删除我字典中的 2 个条目......

[PedObjects setObject:[PedMessage copy] forKey:[PedMessage objectForKey:@"ObjectID"]];
[self performSelector:@selector(delete:) withObject:[PedObjects objectForKey:[PedMessage objectForKey:@"ObjectID"]] afterDelay:2.0];


-(void)delete:(NSMutableDictionary*)dict
{
    NSLog(@"%@",[PedMessage objectForKey:@"ObjectID"]);
    NSLog(@"%@",PedObjects);
    [PedObjects removeObjectForKey:[dict objectForKey:@"ObjectID"]];
    NSLog(@"%@",PedObjects);

}
4

1 回答 1

5

你可以使用这样的东西:

你打电话而不是计时器

[self performSelector:@selector(delete:) withObject:yourDictionary afterDelay:2.0];

//delete implementation

-(void)delete:(NSMutableDictionary*)dict {
    [dict removeObjectForKey:@"yourKey"];
}
于 2012-12-08T16:18:01.613 回答