다음 두 줄의 실행 사이에 지연 추가
(동일한) 함수에서 두 줄의 실행 사이에 지연을 추가해야합니다. 이를 수행하는 데 유리한 옵션이 있습니까?
참고 : 이 작업을 수행하는 데 두 가지 다른 함수가 필요하지 않으며 지연이 다른 함수의 실행에 영향을주지 않아야합니다.
예 :
line 1: [executing first operation];
line 2: Delay /* I need to introduce delay here */
line 3: [executing second operation];
어떤 도움이라도 감사합니다. 미리 감사드립니다 ...
다른 방법을 만들지 않고도 gcd를 사용하여이 작업을 수행 할 수 있습니다.
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"Do some work");
});
코드를 복잡하게 만들고 경쟁 조건을 유발할 수 있으므로 "정말 지연을 추가해야합니까?"라고 자문해야합니다.
다음 NSThread
방법을 사용할 수 있습니다 .
[NSThread sleepForTimeInterval: delay];
그러나 메인 스레드에서이 작업을 수행하면 앱이 차단되므로 백그라운드 스레드에서만 수행하십시오.
또는 Swift에서
NSThread.sleepForTimeInterval(delay)
Swift 3에서
Thread.sleep(forTimeInterval: delay)
이 행은 3 초 후에 선택기 secondMethod를 호출합니다.
[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];
원하는 지연으로 두 번째 작업에 사용하십시오. 코드가 많은 경우 자체 메서드에 배치하고 performSelector:
. UI를 차단하지 않습니다.sleep
편집 : 두 번째 방법을 원하지 않는 경우 performSelector에서 블록을 사용할 수 있도록 카테고리를 추가 할 수 있습니다.
@implementation NSObject (PerformBlockAfterDelay)
- (void)performBlock:(void (^)(void))block
afterDelay:(NSTimeInterval)delay
{
block = [block copy];
[self performSelector:@selector(fireBlockAfterDelay:)
withObject:block
afterDelay:delay];
}
- (void)fireBlockAfterDelay:(void (^)(void))block
{
block();
}
@end
또는 더 깔끔하게 :
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
dispatch_get_current_queue(), block);
}
나는 차례를 시작하기 전에 (그리고 차례의 단계 사이) AI가 일시 중지 해야하는 몇 가지 턴 기반 게임을 가지고 있습니다. 지연이 최선의 해결책 인 다른 더 유용한 상황이있을 것입니다. Swift에서 :
let delay = 2.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { self.playerTapped(aiPlayView) }
Objective-C 호출이 다른지 확인하기 위해 방금 여기로 돌아 왔습니다 (저도 이것도 추가해야합니다).
iOS 4.0 이상을 대상으로하는 경우 다음을 수행 할 수 있습니다.
[executing first operation];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[executing second operation];
});
Like @Sunkas wrote, performSelector:withObject:afterDelay:
is the pendant to the dispatch_after
just that it is shorter and you have the normal objective-c
syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameter withObject
and you will receive it in the selector
you call:
[self performSelector:@selector(testStringMethod:)
withObject:@"Test Test"
afterDelay:0.5];
- (void)testStringMethod:(NSString *)string{
NSLog(@"string >>> %@", string);
}
If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this:
If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
참고URL : https://stackoverflow.com/questions/15335649/adding-delay-between-execution-of-two-following-lines
'IT TIP' 카테고리의 다른 글
Android Studio에서 AVD 에뮬레이터 창의 크기를 조정하는 방법은 무엇입니까? (0) | 2020.11.02 |
---|---|
시작할 때 시작할 프로그램을 어떻게 설정합니까? (0) | 2020.11.02 |
체크 박스 서버 측 PHP가있는 새로운 Google recaptcha (0) | 2020.11.02 |
Redis 서버를 계속 실행하는 방법 (0) | 2020.11.02 |
Android Play 스토어의 베타 버전입니다. (0) | 2020.11.01 |