How can I delay a method call for 1 second?

前端 未结 11 1365
别跟我提以往
别跟我提以往 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:43

    You can use the perform selector for after the 0.1 sec delay method is call for that following code to do this.

    [self performSelector:@selector(InsertView)  withObject:nil afterDelay:0.1]; 
    
    0 讨论(0)
  • 2020-11-30 18:45

    You could also use a block

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [object method]; 
    });
    

    Most of time you will want to use dispatch_get_main_queue, although if there is no UI in the method you could use a global queue.

    Edit:

    Swift 3 version:

    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        object.method()
    }
    

    Equally, DispatchQueue.global().asyncAfter(... might also be a good option.

    0 讨论(0)
  • 2020-11-30 18:47

    There are already a lot of answers and they are all correct. In case you want to use the dispatch_after you should be looking for the snippet which is included inside the Code Snippet Library at the right bottom (where you can select the UI elements).

    enter image description here

    So you just need to call this snippet by writing dispatch in code:

    enter image description here

    0 讨论(0)
  • 2020-11-30 18:48

    There is a Swift 3 solution from the checked solution :

    self.perform(#selector(self.targetMethod), with: self, afterDelay: 1.0)
    

    And there is the method

    @objc fileprivate func targetMethod(){
    
    }
    
    0 讨论(0)
  • 2020-11-30 18:51

    Best way to do is :

    [self performSelector:@selector(YourFunctionName) 
               withObject:(can be Self or Object from other Classes) 
               afterDelay:(Time Of Delay)];
    

    you can also pass nil as withObject parameter.

    example :

    [self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];
    
    0 讨论(0)
  • 2020-11-30 18:54
    performSelector:withObject:afterDelay:
    

    Document Reference

    0 讨论(0)
提交回复
热议问题