0

I have got a problem with saving several data from an array into one context. I try the normal way for me to doing that but if I try to print the data there is only shown [, ] in the console! I don't get it?

Could you help me?

Here is my Code:

override func viewDidLoad() {
    super.viewDidLoad()
    let context: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
    let array = ["Hey", "there", "I", "am", "an", "example"]

    let entityExample = NSEntityDescription.entityForName("Example", inManagedObjectContext: context)
    var newItemExample = Example(entity: entityExample!, insertIntoManagedObjectContext: context)

    for string in array {
        newItemExample.string = string
        println(newItemExample.string)
        context.save(nil)
    }

    let fetchRequest = NSFetchRequest(entityName: "Example")
    var dataExample = [Example]()

    dataExample = context.executeFetchRequest(fetchRequest, error: nil) as [Example]

    println(dataExample) }

What I am doing wrong and how it works?

Tom Kuschka
  • 463
  • 1
  • 8
  • 17

1 Answers1

0

You are creating just one managed object. You should create newEntity in for loop. Or different way don't use for loop. Make your code little bit functional

array.map { word -> Void in
    let newItemExample = Example(entity: entityExample!, insertIntoManagedObjectContext:context)
    newItemExample.string = word
}

var error: NSError?
context.save(&error)
if let error = error {
    println("Error: \(error.localizedDescription)")
}
mustafa
  • 15,254
  • 10
  • 48
  • 57
  • No just [, , , , , , ] – Tom Kuschka Nov 07 '14 at 21:35
  • Ok this code is completely correct. The reason you see dots instead of example.string in console is because of faulting. When you fetch objects from core data it doesn't fetch object's all properties. The properties is fetched when you actually need them. Instead of writing `println(result)` try this `println(result[0].string)` – mustafa Nov 07 '14 at 21:49
  • Cool. Thank You very very much. It works! Have a good evening! – Tom Kuschka Nov 07 '14 at 22:00