Writing / Reading Data Files in OS X

I'm new to OS X development, the Foundation framework and swift. I have some C#.net experience.

I'm trying to figure out how to write and read data files (ints and doubles) to a data file on the hard drive. I've experimented with NSStream, NSFileHandle, writeToFile from NSMutableArray, and any number of other things I've read about on the web.

I need to store away a bunch of test values and read them in later for analysis.

I would appreciate guidance, references, code snippets, or what ever advice someone can offer. Details are very useful as I'm still learning this framework and swift. I've read the stuff on Aple's Developer site and the class references, but I need a little more "help" than that. Thanks - John

The best solution for you is probably the property list format (also known as plist), which uses XML to "serialize" (i.e. convert a network of objects into a single chunk of data) basic dictionary content. Stuff like strings, numbers, dates, or even raw data. Check out the NSPropertyListSerialization class for your reading and writing needs.


To write to a file, you'd use code like this:

//Assume you've got an array or dictionary named "information"

let data = try NSPropertyListSerialization.dataWithPropertyList(array, format:.XMLFormat_v1_0, options:0)

data.writeToURL(/* your data file location */, atomically: false);


To read from a file, you'd use code like this:

let data = NSData(contentsOfURL:/ your data file location */ )

let information = try NSPropertyListSerialization.propertyListWithData(data, options:0, format: nil)

//Use the information


Important: Remember that not everything can go into a property list. More complicated data like images and colors must be flattened into data first using the NSKeyedArchiver and NSKeyedUnarchiver classes. Let me know if you need more help with those.

In addition to the information above, you might want to check out NSJSONSerialization in case you need interoperability with JSON-friendly components or services. A few pieces of documentation you might be interested in:


Reading and Writing Property-List Data in the Property List Programming Guide

Collections Programming Topics

Archives and Serializations Programming Guide

Hi Cesare, could I trouble you to move your post to a new thread? Your question is slightly different than the one addressed here.

I deleted the wrong post.

I'd like Writing/Reading Data Files in OS X from a CoreData Model. Here's my DataModel:


//DataModel.swift
//CoreDataExample
import Foundation
import CoreData
class DataModel: NSManagedObject {
Insert code here to add functionality to your managed object subclass }


//DataModel+CoreDataProperties.swift
//CoreDataExample
import Foundation
import CoreData
extension DataModel {
    @NSManaged var cognome: String?
    @NSManaged var dataNascita: NSDate?
    @NSManaged var nome: String?
}


I'd like to save to a file data from CoreData, but I can't understand which variable I should use instead of array in the saveDataToFile function. I've tried with result but it doesn't work, even if it contains data. I can't as well make working the readFromFile function. Attached below the ViewController.swift file with what I'd like to add.


//ViewController.swift
//CoreDataExample
import Cocoa
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
    @IBOutlet weak var miaTable: NSTableView! 
    @IBOutlet weak var nomeField: NSTextField!
    @IBOutlet weak var cognomeField: NSTextField!
    @IBOutlet weak var dataNascitaField: NSTextField!
  
    var managedContext = (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
  
    override func viewDidLoad() {
        super.viewDidLoad()
        //Do any additional setup after loading the view.
    }
    override var representedObject: AnyObject? {
        didSet {
        //Update the view, if already loaded.
        }
    }
  
    @IBAction func saveDataToFile(sender: NSButton) {
        Initialize Fetch Request
        let fetchRequest = NSFetchRequest(entityName: "DataModel")      
        do {
            let result = try managedContext.executeFetchRequest(fetchRequest) as! [DataModel]
            se result contiene elementi stampa tutti gli elementi
            guard result.count > 0  else {
                print("Non ci sono oggetti registrati")
                return
                }
          
            print("Ci sono \(result.count) oggetti registrati")
            var i=1
            for dati in result as [DataModel] {
                if (dati.nome != nil && dati.cognome != nil && dati.dataNascita != nil) {
                print("\(i) Nome: \(dati.nome!)  Cognome: \(dati.cognome!)  Data di Nascita: \(dati.dataNascita!)")
                    ++i
                }
                else {
                    print("Nome: nil  Cognome: nil  Data di Nascita: nil")
                }
            }
        }
        catch let error as NSError {
            print("Errore nel recupero dei dati \n \(error.localizedDescription)")
            }
      
        let salva_File = NSSavePanel()
        salva_File.extensionHidden = true
        salva_File.canSelectHiddenExtension = true
        salva_File.allowedFileTypes = ["cpa"]
        salva_File.beginWithCompletionHandler { (result:Int) -> Void in
            if result == NSFileHandlingPanelOKButton {
                let fileURL = salva_File.URL
                print(fileURL)
            }
        }
        let dataCoreData = try NSPropertyListSerialization.dataWithPropertyList(result, format: .XMLFormat_v1_0, options: 0)
        if dataCoreData.writeToURL(salva_File.URL!, atomically: false) {
            print("File salvato con successo")
        }
        else {
            print("File non salvato")}
    }
  
    @IBAction func readFromFile(sender: NSButton) {
        let apriFile = NSOpenPanel()
        apriFile.beginWithCompletionHandler { (result:Int) -> Void in
            if result == NSFileHandlingPanelOKButton {
                let data = NSData(contentsOfURL: apriFile.URL)
                let information = try NSPropertyListSerialization.propertyListWithData(data, options:0, format: nil)
            }
        }
    }
}


Best Regards

Cesare Piersigilli

Writing / Reading Data Files in OS X
 
 
Q