2017-02-13 49 views
0

我正在學習Swift(只是一個愛好),並試圖找出我應該如何保存和加載函數到基於文檔的swift應用程序中的document.swift文件?我想知道如何保存和加載簡單的txt文件。我正在使用NSTextView,所以我想我必須將其更改爲NSString?如何將簡單的保存加載函數添加到基於文檔的Swift 3應用程序?

以下是這些功能的時刻:

override func data(ofType typeName: String) throws -> Data { 
     // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. 
     // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. 
     throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)  
    } 

override func read(from data: Data, ofType typeName: String) throws { 
     // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. 
     // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. 
     // If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded. 
     throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) 

    } 

回答

0

在你document.swift以下文件這些功能將加載並設置文本視圖的字符串值。

希望這會有所幫助!

var content = "" 
override func makeWindowControllers() { 
    //Make the window controller 
    let storyboard = NSStoryboard(name: "Main", bundle: nil) 
    let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController 
    self.addWindowController(windowController) 

    //Access the view controller 
    let vc = windowController.contentViewController as! ViewController 
    //Set the text view string to the variable that was loaded 
    vc.textView.string = content 
} 

override func data(ofType typeName: String) throws -> Data { 
    //Access the current view controller 
    if let vc = self.windowControllers[0].contentViewController as? ViewController { 
     //Get the textView's String Value; or call a function that will create a string of what needs to be saved 
     return vc.textView.string?.data(using: String.Encoding.utf8) ?? Data() 
    }else { 
     throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) 
    } 
} 

override func read(from url: URL, ofType typeName: String) throws { 
    do { 
     //Set a string variable to the loaded string 
     //We can't directly set the text views string value because this function is called before the makeWindowControllers() so now text view is created yet. 
     content = try String(contentsOf: url, encoding: String.Encoding.utf8) 
    }catch { 
     throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) 
    } 
} 
+0

謝謝!我進入它並報告是否有任何問題。 – paha

相關問題