我想在不同的时间表中播放声音,例如每3个,每5个,9个之后,22个之后...等等,所以我创建了一个for循环并传递了不同的-2 scheduledTimerWithTimeInterval,就像这样。
-(void)bellsSchedual{
arrBellsListAllData=[EMeditationDBModel getDataFromBellsList:prop.userId];
EMeditationDBProperty *bellProp=[[EMeditationDBProperty alloc]init];
for (int i=0; i<arrBellsListAllData.count; i++)
{
bellProp=[arrBellsListAllData objectAtIndex:i];
NSString *bellsTime=bellProp.bTime;
if ([bellProp.bTimeSchedule isEqualToString:@"after"]) {
bellTimer= [NSTimer scheduledTimerWithTimeInterval: [bellsTime intValue] target: self
selector: @selector(playSound:) userInfo:nil repeats: NO];
}
else if ([bellProp.bTimeSchedule isEqualToString:@"every"]){
bellTimer=[NSTimer scheduledTimerWithTimeInterval:[bellsTime intValue] target: self
selector: @selector(playSound:) userInfo:nil repeats: YES];
}
}
}
问题是我的计时器不是invalidate.if for循环运行只有一次该计时器无效。
答案 0 :(得分:2)
我认为你应该采用NSTimers数组的方法
某处,主要在你的viewDidLoad
中NSMutableArray *arrTimers = [[NSMutableArray alloc] init]
在您的代码中
for (int i=0; i<arrBellsListAllData.count; i++)
{
bellProp=[arrBellsListAllData objectAtIndex:i];
NSString *bellsTime=bellProp.bTime;
if ([bellProp.bTimeSchedule isEqualToString:@"after"]) {
NSTimer *bellTimer= [NSTimer scheduledTimerWithTimeInterval:[bellsTime intValue] target: self
selector: @selector(playSound:) userInfo:nil repeats: NO]
[arrTimers addObject:bellTimer];
}
else if ([bellProp.bTimeSchedule isEqualToString:@"every"]){
NSTimer *bellTimer=[NSTimer scheduledTimerWithTimeInterval:[bellsTime intValue] target: self
selector: @selector(playSound:) userInfo:nil repeats: YES];
[arrTimers addObject:bellTimer];
}
}
循环无效
-(void) invalidateAllTimers{
for( NSTimer *timer in arrTimers) {
[timer invalidate];
}
}
如果您想使特定计时器无效,请使用
[NSTimer scheduledTimerWithTimeInterval:[bellsTime intValue]
target:self
selector:@selector(playSound:)
userInfo:anyId
repeats:NO];
在userInfo对象中传递任何标识符以查找任何特定计时器。
答案 1 :(得分:0)
-(void)bellsSchedual {
arrBellsListAllData = [EMeditationDBModel getDataFromBellsList:prop.userId];
EMeditationDBProperty *bellProp = [[EMeditationDBProperty alloc] init];
for (int i=0; i<arrBellsListAllData.count; i++) {
bellProp = [arrBellsListAllData objectAtIndex:i];
NSString *bellsTime = bellProp.bTime;
if ([bellProp.bTimeSchedule isEqualToString:@"after"]) {
[NSTimer scheduledTimerWithTimeInterval:[bellsTime intValue]
target:self
selector:@selector(playSound:)
userInfo:nil
repeats:NO];
} else if ([bellProp.bTimeSchedule isEqualToString:@"every"]){
[NSTimer scheduledTimerWithTimeInterval:[bellsTime intValue] target: self
target:self
selector:@selector(playSound:)
userInfo:nil
repeats:YES];
}
}
}