在NSMutableDictionary中存储NSTimer对象
问题描述:
使用iphone sdk 4.o.我试图在NSMutableDictionay中存储大约10个NSTimer对象,然后通过键索引它们。这是为了节省10个不同的startTimer,stopTimer函数。我已经这样做了,但是很担心内存泄漏问题在NSMutableDictionary中存储NSTimer对象
下面的代码是否安全,是否可以将定时器对象复制到字典中。 TimerList是NSMutableDictionary类型的一个属性。
-(IBAction)startTimer:(NSNumber)identifier
{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:7
target:self selector:@selector(timerFireMethod:)
userInfo:nil repeats:YES];
[self.TimerList setObject:timer forKey: identifier];
}
-(IBAction)stopTimer:(NSNumber)identifier
{
NSTimer* timer = [self.ReRegisterTimerList objectForKey: identifier];
[timer invalidate];
[self.TimerList setObject:nil forKey: identifier];
}
-(void)timerFireMethod:(NSTimer*)theTimer
{
if (theTimer == [self.TimerList objectForKey:someKey])
{
found = true;
// do something if its a certain timer
}
}
答
请注意,您可以通过指针采取类类型的实例,即它应该是NSNumber*
不NSNumber
。
否则,它看起来好像没什么问题 - 只要记住-invalidate
特殊考虑:
您必须在其上安装了定时器线程发送此消息。