How to save an array in master data (Swift)

My code reads a text file and stores the contents of the file in an array. I am having problems with the next step; passing the contents of the array to Core Data. A .txt file is just a short list of fruits. The essence is “Fruit,” and the attribute is “fruit name.”

When I print, only the last element of the array appears. Here is 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 result of both println statements ....

// Println of fruitArray apple Apricot Banana blueberries blackberries blueberries Coconut Cranberries Date Dragonfruit figs guayava grapes Nectar kiwi Lemon Lime nephelium mango Melon orange Papaya Pineapple Raspberry Star fruit strawberry Watermelon

// Printout of master data

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

- , , fruitArray ? .

+4
1

newFruit. , for fruit in fruitArray fruitname.

:

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

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

All Articles