0

I have an array of custom objects but when I add items to array it creates duplicate of last item add in array. Below is my code, please suggest where is the mistake, this small thing not able to get it.

var tempArr:[AnimalViewModel] =  [AnimalViewModel]()

        do {

            var objAnimal = Animal()

            var result = try managedContext.fetch(fetchRequest)
            for ds in result as! [NSManagedObject] {

            objAnimal.name = (ds.value(forKey: "name")) as! String
            objAnimal.type = (ds.value(forKey: “type”)) as! String

                Var objAVM = AnimalViewModel(aniModel: objAnimal)
                tempArr.append(objAVM)

            }
        } catch {
            print(" Error ")
        }

The array tempArr contains all duplicate element as last inserted element even objAnimal contains different values.

Thanks,

1
  • Create a new Animal each time inside the for loop. Even better is to have your fetch request return an array of your entity class and use that as a parameter when calling the AnimalViewModel constructor Commented Feb 7, 2019 at 17:35

1 Answer 1

1

First of all never print a meaningless literal string like "Error" in a catch block. Print always the error instance.

Animal is obviously a class (reference type). You are creating one instance and the properties are updated in the loop. As always the same instance is used the values are overwritten and you get result.count items with the same contents.

Create new instances inside the loop and replace Entity with the real entity name

var tempArr = [AnimalViewModel]()

do {
    let result = try managedContext.fetch(fetchRequest) as! [Entity] // let !
    for ds in result {

        let objAnimal = Animal()  // let !
        objAnimal.name = ds.name
        objAnimal.type = ds.type

        let objAVM = AnimalViewModel(aniModel: objAnimal)  // let !
        tempArr.append(objAVM)
    }
} catch {
    print(error)
}

And please notice and fix the warnings about never mutated variables

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.