我已经创建了一个小应用程序,它有一个带有段和UITableView的UISegmentedControl。当选定的段更改时,TableView中的数据(从服务器下载)应该更改。因此我有一个方法
- (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)
我该如何解决这个问题?
答案 0 :(得分:1)
您应该将调度逻辑移出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
或类似的内容中将其停止。