gpt4 book ai didi

ios - 是否有可能永远不会在线程中调用延迟调用?

转载 作者:行者123 更新时间:2023-11-28 20:16:30 25 4
gpt4 key购买 nike

假设您将计时器附加到特定线程中的运行循环,但该线程在计时器被触发之前已经退出,导致该方法无法执行。这种情况可能吗?

最佳答案

当然这是可能的,而且很容易证明。

#import <Foundation/Foundation.h>

#define TIMER_INTERVAL 2.0

@interface Needle : NSObject

- (void)sew;
- (void)tick:(NSTimer *)tim;

@end

@implementation Needle
{
NSTimer * tim;
}

- (void)sew
{
@autoreleasepool{
tim = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL
target:self
selector:@selector(tick:)
userInfo:nil
repeats:NO];

while( ![[NSThread currentThread] isCancelled] ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
}
}

- (void)tick:(NSTimer *)timer
{
NSLog(@"Let's get the bacon delivered!");
[[NSThread currentThread] cancel];
}

@end

int main(int argc, const char * argv[])
{

@autoreleasepool {

Needle * needle = [Needle new];
NSThread * thread = [[NSThread alloc] initWithTarget:needle
selector:@selector(sew)
object:nil];

[thread start];
// Change this to "+ 1" to see the timer fire.
NSTimeInterval interval = TIMER_INTERVAL - 1;
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:interval]];
[thread cancel];

}
return 0;
}

关于ios - 是否有可能永远不会在线程中调用延迟调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com