为什么尝试设置我的NSProgressIndicator的值会使我的应用程序崩溃?

时间:2016-08-25 00:06:10

标签: swift null optional nsprogressindicator

尝试从URLSessionDownloadTask设置进度时,出现unexpectedly found nil while unwrapping an Optional value错误。我想要完成的是拥有一个单独的类URLSessionDownloadDelegate,处理下载并更新必要的UI元素,在本例中为NSProgressIndicator。这是我的代码:

AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

@IBOutlet weak var window: NSWindow!
@IBOutlet var button: NSButton!
@IBOutlet var progind: NSProgressIndicator!


@IBAction func update(_ sender:AnyObject){
    button.isEnabled = false
    updater().downloadupdate(arg1: "first argument")
}

func applicationDidFinishLaunching(_ aNotification: Notification) {
    progind.doubleValue = 50.0 //me trying to test if the progress indicator even works
}

func applicationWillTerminate(_ aNotification: Notification) {
}
func updateDownload(done: Double, expect: Double){
    print(done)
    print(expect)
    progind.maxValue = expect //this line crashes from the unexpected nil error
    progind.doubleValue = done //so does this one, if I delete the one above
}
}

updater.swift

import Foundation

class updater: NSObject, URLSessionDelegate, URLSessionDownloadDelegate {



func downloadupdate(arg1: String){
    print(arg1)
    let requestURL: URL = URL(string: "https://www.apple.com")!
    let urlRequest: URLRequest = URLRequest(url: requestURL as URL)

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)

    let downloads = session.downloadTask(with: urlRequest)

    print("starting download...")
    downloads.resume()
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
    print("download finished!")
    print(location)
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    let expectDouble = Double(totalBytesExpectedToWrite)
    let doneDouble = Double(totalBytesWritten)
    AppDelegate().updateDownload(done: doneDouble, expect: expectDouble)
}
}

我试过替换

 AppDelegate().updateDownload(done: doneDouble, expect: expectDouble)

 AppDelegate().progind.maxValue = expect 
 AppDelegate().progind.doubleValue = done

并得到了相同的结果。

我实际上认为我知道造成这种情况的原因。我的研究让我相信我实际上宣布AppDelegate的新实例,其中progind甚至不存在!那么如何正确设置progind的值,同时在updater.swift中保留尽可能多的进程?

1 个答案:

答案 0 :(得分:0)

你是对的,当你输入AppDelegate()时,你正在创建一个新对象。因为它是新的,所以它没有按照故事板或xib的方式进行初始化的任何出口。

您需要获取代表您的应用程序的共享单例(请参阅NSApplication docs),询问它的委托,将其转换为AppDelegate,并在那里设置属性。

示例代码(Swift 2.2):

if let delegate = NSApplication.sharedApplication().delegate as? AppDelegate {
    delegate.progind.maxValue = expected
} else {
    print("Unexpected delegate type: \(NSApplication.sharedApplication().delegate)")
}