简体   繁体   中英

for 1 second: objective c coding help

Is it possible to do something like this?

if (myVariable == 100 for more than 1 second) {
}

So if myVariable equals 100 for more than 1 second do something.

Thanks! Elijah

You can store the time when you set myVariable to a new value (easy if you use a setter method for this all over the place). Then start a timer that fires after a second and check if you didn't change the value in meantime.

It's an unusual pattern though, and there are probably better ways to do what you try to accomplish.

I guess something like that is not possible. Different approach probably could solve that. ie you can leave some kind of a timestamp every time when someone changes myVariable and then just see how much has passed since the last change.

You could start an NSTimer from within the body of the if() statement that has a timer of 1 second. So something like

if(myVariable >= 100 && myTimer == nil){
    //NSTimer code here
}else if(myVariable < 100 && myTimer !=nil){
    //Invalidate timer
    //Set myTimer to nil
}

If you get the timer to call a method that then does what you want.

This should work but I can't help but feel there is a better solution to the actual problem your trying to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM