OSX: 在屏幕保护程序中创建线程

OSX: Creating a thread in a screensaver

我正在为 OSX 创建一个简单的屏幕保护程序,并想为一些后台计算创建一个线程。

我在 SO 中找到了这个函数,它将在 X 秒后创建一个线程:

func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) {
        if(background != nil){ background!(); }

        let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(popTime, dispatch_get_main_queue()) {
            if(completion != nil){ completion!(); }
        }
    }
}

但是当我把它添加到init时它似乎不起作用:

override init?(frame: NSRect, isPreview: Bool) {
    super.init(frame: frame, isPreview: isPreview);
    let fontSize: CGFloat = 20;
    let frameHeight: CGFloat = self.frame.size.height;
    let font = NSFont(name: "Times New Roman", size: fontSize);
    let paragraph = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle;
    paragraph.alignment = NSTextAlignment.Center;
    let textColor = NSColor(calibratedRed: 255.0, green: 255.0, blue: 255.0, alpha: 1.0);

    self.backgroundThread(3.0, background: {

        let w:String = "test";
        let textRect: NSRect = NSMakeRect(1, (frameHeight-CGFloat(fontSize*CGFloat(1))-30), 80, 30);
        if let actualFont = font {
            let textFontAttributes = [
                NSFontAttributeName: actualFont,
                NSForegroundColorAttributeName: textColor,
                NSParagraphStyleAttributeName: paragraph
            ];

            w.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes);
        }
    });
}

它应该在 3 秒后在不同的线程中显示该字符串,但它没有。我错过了什么?

GUI线程必须是主线程,不能是后台线程

所以使用完成闭包

self.backgroundThread(3.0, completion: {

或者只使用必要的代码

dispatch_after(3.0, dispatch_get_main_queue()) {
    ...
}

或者使用像Eki

这样的框架