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()
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)
}
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)
var request = NSFetchRequest(entityName: "Fruit")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
println(results)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
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 ? .