List append on for loop - Swift 3 / Xcode 8 [closed]

1

I'm having a problem adding items to a list inside the 'for' loop, where all items in the list are repeated with the last value entered.

Here's my NSManagedObject list

 var  listCursosNovos: [Cursos] = []

Here's my loop:

for i in 0..<JSON.count{
  var resultadoWS = JSON[i] as [String:AnyObject]!

  curso.codcurso = resultadoWS?["COD_CURSO"] as? String

  //Here I see that 'curso' comes as I wanted it  
  print("Add curso: ",curso)

self.listCursosNovos.append(curso) //Here is the problem
}

Each 'course' item is shown to me on the console and everything works fine. The problem is that when I put this item in the list, it repeats the last value I entered. Example:

If I have 3 items within 'JSON' with the values:

{codcurso = "Zezinho"}
{codcurso = "Huginho"}
{codcurso = "Luizinho"}

After getting out of the loop and checking the result of my list

print("The final list is:",self.listCursosNovos)

They look like this:

{codcurso = "Luizinho"}
{codcurso = "Luizinho"}
{codcurso = "Luizinho"}

This is repeated regardless of how many items I have inside 'JSON' and the value repeated is always the last, I can not understand why

I hope someone can help me. Thank you!

    
asked by anonymous 23.01.2017 / 01:34

1 answer

0

As a user here helped me, the solution was to create a new 'course' type object with each loop. I did not pay attention to this and was creating it before entering my loop

for i in 0..<JSON.count{
  var resultadoWS = JSON[i] as [String:AnyObject]!
  let curso = Cursos(context: contexto)//Here is the solution

  curso.codcurso = resultadoWS?["COD_CURSO"] as? String

  //Here I see that 'curso' comes as I wanted it  
  print("Add curso: ",curso)

self.listCursosNovos.append(curso)
}
    
23.01.2017 / 12:02