simnik
simnik

Reputation: 483

Store Array of custom Objects Swift

I have a class called "Entry".

in there I have different variables like Int, NSDate and Float.

I have an array "listData" which consist of these elements.

This "listData" is filling a TableView. How do I store and read this array? How would an implementation look like?

I have tried to iterate through the array and saving the single elements of the "Entry" class to put it back together while loading. It does not seem to work properly.

Here is some of my code:

My Entry Class:

import Foundation

class Entry  {

let number      : Int
let date        : NSDate
let mileage     : Int
let trip        : Float
let speed       : Float
let consumption : Float

init(number: Int, date: NSDate, mileage: Int, trip: Float, speed: Float, consumption: Float) {


    self.number         = number
    self.date           = date
    self.mileage        = mileage
    self.trip           = trip
    self.speed          = speed
    self.consumption    = consumption
    }
}

Then I have a global variable for the array:

var listData = [Entry]()

On a second ViewController I have declared some Variables which take the input of Textfield, to save them to a new "Entry" Object, which will then be appended to the listData Array:

listData.append(Entry(number: number_pass, date: date_pass, mileage: mileage_pass, trip: trip_pass, speed: speed_pass, consumption: consumption_pass))

Everything else I have in code is just setting up and managing the Tableviews.

Is there a way to use UserDefaults? Or do I have to use CoreData?

Hope You can help! Cheers, Niklas

Upvotes: 0

Views: 2491

Answers (1)

Prontto
Prontto

Reputation: 1681

If you don't want to use NSUserDefaults, you can use Core Data. This first class is just for make things easier:

class CoreDataHelper: NSObject {

    class func insertManagedObject(className: String, moc: NSManagedObjectContext) ->AnyObject {
        let managedObject: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(className, inManagedObjectContext: moc) as! NSManagedObject
        return managedObject
    }

    class func fetchEntities(className: String, withPredicate predicate: NSPredicate?, moc: NSManagedObjectContext) -> NSArray {
        let request: NSFetchRequest = NSFetchRequest()
        let entityDescription: NSEntityDescription = NSEntityDescription.entityForName(className, inManagedObjectContext: moc)!

        request.entity = entityDescription

        if predicate != nil {
            request.predicate = predicate!
        }

        request.returnsObjectsAsFaults = false

        let items: NSArray = moc.executeFetchRequest(request, error: nil)!
        return items
     }

}

And in your ViewController:

@IBOutlet weak var myTableView: NSTableView!

// Your datastore
private var myArray = [Entry]()

// ManagedObjectContext
lazy var moc: NSManagedObjectContext? = {
    let appi = NSApplication.sharedApplication().delegate as! AppDelegate
    if let moc = appi.managedObjectContext {
        return moc
    } else {
        return nil
    }
    }()

func reloadTableView(sender: AnyObject) {
    let request = NSFetchRequest(entityName: "Entry")

    // Just an example of sort descriptor
    request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]

    var anyerror: NSError?

    let fetchedEntries = moc?.executeFetchRequest(request, error: &anyerror)

    if fetchedEntries == nil {
        println("Error fetching: \(anyerror)")
        return
    }

    myArray = fetchedEntries as! [Entry]

    myTableView.reloadData()
}

// Life cycle
override func viewDidLoad() {
    super.viewDidLoad()

    reloadTableView(self)

}

Upvotes: 1

Related Questions