Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you store an array in core data (Swift)

My code reads a text file and stores the contents of the file in an array. I'm having trouble with the next step; transferring the contents of the array into Core Data. The .txt file is just a short list of fruits. The entity is "Fruit" and the attribute is "fruitname".

Only the last array element is showing up when I print. Here's my code:-

    import UIKit
    import CoreData

    class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    // STORE .TXT FILE IN ARRAY.....
    let bundle = NSBundle.mainBundle()
    let fruitList = bundle.pathForResource("List of Fruits", ofType: "txt")

    let fruitArray = String(contentsOfFile: fruitList!, encoding: NSUTF8StringEncoding, error: nil)!.componentsSeparatedByString("\r")


    for x in fruitArray {
        println(x)

    }

    // STORE FRUIT-ARRAY IN CORE DATA......
    var appDel = UIApplication.sharedApplication().delegate as AppDelegate

    var context : NSManagedObjectContext! = appDel.managedObjectContext!

    var newFruit = NSEntityDescription.insertNewObjectForEntityForName("Fruit", inManagedObjectContext: context) as NSManagedObject

    for fruit in fruitArray {

        newFruit.setValue(fruit, forKey: "fruitname")
    }

    context.save(nil)


    // RETRIEVE AND PRINT STORED VALUES....
    var request = NSFetchRequest(entityName: "Fruit")
    request.returnsObjectsAsFaults = false

    var results = context.executeFetchRequest(request, error: nil)

    println(results)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

This is the output from both println statements....

// Println of fruitArray Apple Apricot Banana Bilberry Blackberry Blueberry Coconut Cranberry Date Dragonfruit Fig Grape Guava Honeydew Kiwi Lemon Lime Lychee Mango Melon Orange Papaya Pineapple Raspberry Star fruit Strawberry Watermelon

//Println of core data

Optional(........ fruitname = Watermelon; })]

Can someone please help make sure that everything in fruitArray gets saved in core data? Thanks in advance.

like image 881
BadLuckJ Avatar asked Feb 24 '15 04:02

BadLuckJ


1 Answers

You have only created one newFruit. Thus, your for fruit in fruitArray loop is just repeatedly reassigning the fruitname property.

Change your code to:

for fruit in fruitArray {
  var newFruit = NSEntityDescription.insertNewObjectForEntityForName ("Fruit", 
     inManagedObjectContext: context) as NSManagedObject

  newFruit.setValue(fruit, forKey: "fruitname")
}
like image 125
GoZoner Avatar answered Nov 16 '22 23:11

GoZoner