我在循环中创建了很多计时器,以便将单元格添加到TableView:
for (NSInteger i = 0; i < media.products.count; i++) {
NSDictionary *obj = [media.products objectAtIndex:i];
NSInteger timeInterval = [[obj objectForKey:@"TIME"] integerValue];
[NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(addNewProductToTableView:) userInfo:obj repeats:NO];
}
我希望在显示另一个控制器时取消所有这些控制器,例如:shouldSelectViewController或viewWillDisappear:
NSLog(@"I've been called!");
// Doesn't seem to work :
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[NSTimer cancelPreviousPerformRequestsWithTarget:self];
// Clean the table
self.dataSource = [NSMutableArray array];
[self.tableView reloadData];
当再次显示tableView时,前一个和当前定时器的混合会使单元格显示混乱。
或者我不介意破坏整个控制器,如果它更简单,但也无法让它工作。
self.view = nil; // ?
答案 0 :(得分:2)
在viewcontroler
NSMutableArray *timers;
在viewDidload timers = [[NSMutableArray alloc]init];
将循环代码更改为
for (NSInteger i = 0; i < media.products.count; i++) {
NSDictionary *obj = [media.products objectAtIndex:i];
NSInteger timeInterval = [[obj objectForKey:@"TIME"] integerValue];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(addNewProductToTableView:) userInfo:obj repeats:NO];
[timers addObject:timer];
}
无论你想让计时器无效
for (NSTimer *timer in timers)
[timer invalidate];
}
答案 1 :(得分:1)
cancelPreviousPerformRequestsWithTarget
与NSTimer
无关。他们取消了使用performSelector:withObject:afterDelay:
(及其随播广告performSelector:withObject:afterDelay:inModes:
)安排的来电。您需要做的是将您创建的计时器保留在属性中,并在需要取消时使其无效:
@protocol (nonatomic) NSTimer *timer;
...
self.timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(addNewProductToTableView:) userInfo:obj repeats:NO];
...
[self.timer invalidate];
self.timer = nil;