NSTimer가 호출 한 메소드에 매개 변수 전달
NSTimer에 의해 호출되는 메소드에 매개 변수를 어떻게 전달할 수 있습니까? 내 타이머는 다음과 같습니다.
[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES];
updateBusLocation 메서드에 문자열을 전달할 수 있기를 원합니다. 또한 updateBusLocation 메소드를 어디에 정의해야합니까? 타이머를 만든 동일한 .m 파일에서?
편집하다:
사실 여전히 문제가 있습니다. 오류 메시지가 나타납니다.
포착되지 않은 예외 'NSInvalidArgumentException'으로 인해 앱 종료, 이유 : ' * -[MapKitDisplayViewController updateBusLocation] : 인스턴스 0x4623600으로 전송 된 인식 할 수없는 선택기'
내 코드는 다음과 같습니다.
- (IBAction) showBus {
//do something
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateBusLocation) userInfo:txtFieldData repeats:YES];
[txtFieldData release];
}
- (void) updateBusLocation:(NSTimer*)theTimer
{
NSLog(@"timer method was called");
NSString *txtFieldData = [[NSString alloc] initWithString:(NSString*)[theTimer userInfo]];
if(txtFieldData == busNum.text) {
//do something else
}
}
편집 # 2 : 귀하의 예제 코드가 도움을 주셔서 감사합니다.
타겟에서 메소드를 정의해야합니다. 대상을 'self'로 설정 했으므로 동일한 개체가 메서드를 구현해야합니다. 하지만 목표를 원하는대로 설정할 수 있습니다.
userInfo는 원하는 객체 (또는 컬렉션)에 설정할 수있는 포인터이며 타이머가 실행될 때 대상 선택기로 전달됩니다.
도움이 되었기를 바랍니다.
편집 : ... 간단한 예 :
타이머 설정 :
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(handleTimer:)
userInfo:@"someString" repeats:NO];
동일한 클래스에서 핸들러를 구현합니다 (대상을 'self'로 설정한다고 가정).
- (void)handleTimer:(NSTimer*)theTimer {
NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]);
}
userInfo로 인수를 전달할 수 있습니다.[NSDictionary dictionaryWithObjectsAndKeys:parameterObj1, @"keyOfParameter1"];
간단한 예 :
[NSTimer scheduledTimerWithTimeInterval:3.0
target:self
selector:@selector(handleTimer:)
userInfo:@{@"parameter1": @9}
repeats:NO];
- (void)handleTimer:(NSTimer *)timer {
NSInteger parameter1 = [[[timer userInfo] objectForKey:@"parameter1"] integerValue];
}
대한 스위프트 4.0 :
원하는 매개 변수가있는 함수를 가질 수 있으며 "scheduledTimer"블록을 사용하여 반복해야하는 코드를 실행할 수 있습니다.
func someFunction(param1: Int, param2: String) {
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print(param1)
print(param2)
}
}
Be careful to call timer.invalidate() when you finish to prevent it from running continuously.
For Swift do like this,
For example you wants to send UILabel with NSTimer
override func viewDidLoad() {
super.viewDidLoad()
var MyLabel = UILabel()
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("callMethod:"), userInfo: MyLabel, repeats: false)
}
func callMethod(timer:NSTimer){
var MyLabel:UILabel = timer.userInfo as UILabel
}
Additional example in Swift using Dictionary literal for passing parameters to the method called by NSTimer:
override func viewDidLoad() {
super.viewDidLoad()
let dictionary: [String : AnyObject] = ["first element" : "Jordan",
"second element" : Int(23)]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0.41),
target: self,
selector: "foo:",
userInfo: dictionary,
repeats: false)
}
func foo(timer: NSTimer) {
let dictionary: [String : AnyObject] = timer.userInfo! as! [String : AnyObject]
let firstElement: String = dictionary["first element"] as! String
let secondElement: Int = dictionary["second element"] as! Int
print("\(firstElement) - \(secondElement)")
}
Not a direct answer to the question but since i ran into this while searching and i needed something different it may help someone. I wanted to call a funciton in a helper class, that i needed to pass in the UIViewController
, rather than passing it with the userinfo which would not allow me to call the function manually elsewhere i created another function which the timer would call and called the function that i was interested in from there. A workaround that helped.
Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats:true);
func timerFired() {
myFunction(controller: self)
}
참고URL : https://stackoverflow.com/questions/4011297/passing-parameters-to-the-method-called-by-a-nstimer
'UFO ET IT' 카테고리의 다른 글
속성 데코레이터를 사용하여 속성을 설정하는 방법은 무엇입니까? (0) | 2020.12.03 |
---|---|
언제 save !, create!를 사용합니까? (0) | 2020.12.03 |
명령 줄에서 대기열과 바인딩을 생성하는 RabbitMQ (0) | 2020.12.03 |
Heroku H18 오류를 어떻게 해석해야합니까? (0) | 2020.12.03 |
jQuery.attr () 함수를 사용하여 여러 데이터 속성을 설정할 수 있습니까? (0) | 2020.12.03 |