在使用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)操作。