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

标签 ios objective-c nsthread nsrunloop

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

最佳答案

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

#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/

相关文章:

ios - 错误 : Value of type 'AppDelegate?' has no member 'present'

ios - NSObject 如何知道它是在哪个 View 中绘制的

ios - 定位和缩放启动屏幕图像

ios - 使用 do while 循环设置背景加载

objective-c - 如何将 NSTimeInterval 对象传递给 detachNewThreadSelector withObject 参数?

ios - ZBarReaderViewController 阅读器 View 更改了 iOS6 和 iOS7 的方向,即使在被 _reader.supportedOrientationsMask 限制后也是如此

ios - 你能找出用户安装了哪些应用程序吗?

ios - 从 UITableView 获取 "Pull to Refresh"的最佳方法是什么?

iphone - 音频/语音可视化

ios - 从 ALAssetsLibrary 返回 UIImages 的 NSArray