[英]NSInvocation & NSTimer - Method gets called twice
我創建了一個小應用程序,該應用程序具有一個UISegmentedControl(帶有to段)和一個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];
}
}
這是我的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
或類似的名稱中將其停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.