IOS語(yǔ)法關(guān)于NStimer中scheduledTimerWithTimeInterval方法傳參的問(wèn)題

iOS
小云
104
2023-09-21 04:02:38

在使用scheduledTimerWithTimeInterval方法創(chuàng)建NSTimer時(shí),如果需要傳遞參數(shù),可以使用userInfo參數(shù)來(lái)傳遞額外的數(shù)據(jù)。

下面是一個(gè)示例代碼:

- (void)startTimerWithInterval:(NSTimeInterval)interval {
NSDictionary *userInfo = @{@"param1": @"value1", @"param2": @"value2"};
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(timerFired:)
userInfo:userInfo
repeats:YES];
}
- (void)timerFired:(NSTimer *)timer {
NSDictionary *userInfo = timer.userInfo;
NSString *param1 = userInfo[@"param1"];
NSString *param2 = userInfo[@"param2"];
// 使用傳遞的參數(shù)進(jìn)行相關(guān)操作
NSLog(@"param1: %@, param2: %@", param1, param2);
}

startTimerWithInterval方法中,通過(guò)userInfo參數(shù)將需要傳遞的參數(shù)存儲(chǔ)在一個(gè)NSDictionary對(duì)象中。然后,在timerFired:方法中,通過(guò)timer.userInfo獲取到傳遞的參數(shù),并進(jìn)行相關(guān)操作。

0