我创建了一个小应用程序,它有一个UISegmentedControl和一个UITableView。当选定的段发生更改时,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];
}
}
这是我的视图DidLoad
- (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
或类似的程序中停止它。