How can I delay a method call for 1 second?

前端 未结 11 1366
别跟我提以往
别跟我提以往 2020-11-30 18:19

Is there an easy way delay a method call for 1 second?

I have a UIImageView that reacts on a touch event. When the touch is detected, some animations ha

相关标签:
11条回答
  • 2020-11-30 18:55

    You can do this

    [self performSelector:@selector(MethodToExecute) withObject:nil afterDelay:1.0 ];
    
    0 讨论(0)
  • 2020-11-30 18:56

    Swift 2.x

    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
     dispatch_after(delayTime, dispatch_get_main_queue()) {
     print("do some work")
    }
    

    Swift 3.x --&-- Swift 4

    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        print("do some work")
    }
    

    or pass a escaping closure

    func delay(seconds: Double, completion: @escaping()-> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: completion)
    }
    
    0 讨论(0)
  • 2020-11-30 18:58

    NOTE: this will pause your whole thread, not just the one method.
    Make a call to sleep/wait/halt for 1000 ms just before calling your method?

    Sleep(1000); // does nothing the next 1000 mSek
    
    Methodcall(params); // now do the real thing
    

    Edit: The above answer applies to the general question "How can I delay a method call for 1 second?", which was the question asked at the time of the answer (infact the answer was given within 7 minutes of the original question :-)). No Info was given about the language at that time, so kindly stop bitching about the proper way of using sleep i XCode og the lack of classes...

    0 讨论(0)
  • 2020-11-30 19:01

    Use in Swift 3

    perform(<Selector>, with: <object>, afterDelay: <Time in Seconds>)
    
    0 讨论(0)
  • 2020-11-30 19:03

    You can also:

    [UIView animateWithDuration:1.0
                     animations:^{ self.view.alpha = 1.1; /* Some fake chages */ }
                     completion:^(BOOL finished)
    {
        NSLog(@"A second lapsed.");
    }];
    

    This case you have to fake some changes to some view to get the animation work. It is hacky indeed, but I love the block based stuff. Or wrap up @mcfedr answer below.


    waitFor(1.0, ^
    {
        NSLog(@"A second lapsed");
    });
    

    typedef void (^WaitCompletionBlock)();
    void waitFor(NSTimeInterval duration, WaitCompletionBlock completion)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC),
                       dispatch_get_main_queue(), ^
        { completion(); });
    }
    
    0 讨论(0)
提交回复
热议问题