NSInvocation&NSTimer - 方法被调用两次
问题描述:
我创建了一个小应用程序,它具有一个UISegmentedControl与段和一个UITableView。当所选段更改时,TableView中的数据(从服务器下载)应该会更改。因此,我有一个方法NSInvocation&NSTimer - 方法被调用两次
- (void)loadPlanForIndex:(int)tableIndex
{
// Create PlanModel and get elements
_planModel =[[PlanModel alloc] init];
_plan = [_planModel getPlanForDayIndex:tableIndex];
// Reload TableView data
[self.firstTable reloadData];
// Set SegmentedControl title
NSString *segmentTitle = @„MyTitle“;
[self.daySegmentedControl setTitle:segmentTitle forSegmentAtIndex:tableIndex];
// Create NSInvocation to call method with parameters
NSInteger objIndex = tableIndex;
SEL selector = @selector(loadPlanForIndex:);
NSMethodSignature *signature = [self methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:selector];
[invocation setArgument:&objIndex atIndex:2];
NSTimeInterval timeInterval = 10;
[NSTimer scheduledTimerWithTimeInterval:timeInterval invocation:invocation repeats:NO];
}
tableIndex是一个索引来获取正确的数据。 前两行获取tableView的数据。
此方法被调用每一个段发生变化时
- (IBAction)didSelectSegment:(id)sender
{
if (self.daySegmentedControl.selectedSegmentIndex == 0)
{
[self loadPlanForIndex:0];
}
else
{
[self loadPlanForIndex:1];
}
}
这是我的viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Some other setup
[self loadPlanForIndex:1];
[self loadPlanForIndex:0];
}
所以,现在这里是我的问题:时间用完,并再次调用该方法时,都会我的viewDidLoad的两个语句被调用(我用NSLog语句检查过)。因此,在应用程序中显示索引1的数据,并且只有在显示正确的数据(用于索引0)后
我该如何解决这个问题?
答
您应该移出调度逻辑关loadPlanForIndex:
方法
- (void)loadPlanForIndex:(int)tableIndex
{
// Create PlanModel and get elements
_planModel =[[PlanModel alloc] init];
_plan = [_planModel getPlanForDayIndex:tableIndex];
// Reload TableView data
[self.firstTable reloadData];
- (void) scheduleAutoReload
// Set SegmentedControl title
NSString *segmentTitle = @„MyTitle“;
[self.daySegmentedControl setTitle:segmentTitle forSegmentAtIndex:tableIndex];
// Create NSInvocation to call method with parameters
NSInteger objIndex = tableIndex;
SEL selector = @selector(loadPlanForIndex:);
NSMethodSignature *signature = [self methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:selector];
[invocation setArgument:&objIndex atIndex:2];
NSTimeInterval timeInterval = 10;
[NSTimer scheduledTimerWithTimeInterval:timeInterval invocation:invocation repeats:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadPlanForIndex:1];
[self scheduleAutoReload];
}
注意到NSTimer
是repeats
现在。我不能运行这个,但我认为它应该工作。无论如何,你可能想把这个定时器保存在一个变量中,所以你可以在viewDidDisappear
或类似的东西中停止它。
很酷,谢谢你的工作!你也知道为什么它做了这些奇怪的事情吗? – Codey 2014-08-30 15:45:20
因为你的方法不断调用自己,并且再次调用它只是开始新的循环而不停止前面的循环。 – tia 2014-08-30 16:07:42
好的,谢谢! – Codey 2014-08-30 16:21:24