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

时间:2016-02-01 18:21:58

标签: multithreading swift macos 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秒后在另一个线程中显示该字符串,但它不会。我错过了什么?

1 个答案:

答案 0 :(得分:2)

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

所以使用完成闭包

self.backgroundThread(3.0, completion: {

或仅使用必要的代码

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

或使用像Eki

这样的框架