CoreData saves data twice when calling saveContext()

428 Views Asked by At

I am currently building a story feature in my iOS app. Like on Instagram and Snapchat. The story also has a circle around the image. It changes the color if the story has been seen.

At the start of the App, I save some values in CoreData to identify every story.

        var context: NSManagedObjectContext!
        var storys = [Story]()
        
        
        private init() {
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            context = appDelegate.persistentContainer.viewContext
            fetchStoryItems()
        }
    
        func addStorys(with shoeID: String, raffles: String, seenStory: Bool) {
            let storyItem = NSEntityDescription.insertNewObject(forEntityName: "Story", into: context) as! Story
            
            storyItem.shoeID = shoeID
            storyItem.newRaffles = raffles
            storyItem.seen = seenStory
            
            if !storys.contains(where: {$0.shoeID == shoeID}) {
                
                    storys.append(storyItem)
                    saveContext()
               
            }
            
            
        }

   func fetchStoryItems() {
        let request: NSFetchRequest<Story> = NSFetchRequest<Story>(entityName: "Story")

        do {

            let storyItemsArray = try context.fetch(request)

            storys = storyItemsArray

        } catch {
            print(error.localizedDescription)
        }
    }
    
    
    func saveContext() {
        do {
            try context.save()
        } catch {
            print(error.localizedDescription)
        }
    }

This works fine and every value is stored once in CoreData. So that the circle is displayed in the correct color, I change the value if the story has been seen. If the user taps von a story the following methods are executed.

  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        CoreDataStoryCheck.sharedInstance.storyTapped(with: Array(storyShoeModel.values)[indexPath.row].ID!, seenStory: true)
        collectionViewOrTableView = 1
        performSegue(withIdentifier: "details", sender: indexPath.row)
    }
    
        func storyTapped(with shoeID: String, seenStory: Bool) {
            
            if let story = storys.first(where: {$0.shoeID == shoeID && $0.seen == false}) {
                story.setValue(true, forKey: "seen")
                saveContext()
            }
    
        }

Now here comes my issue: Every time I am calling this method my data duplicates in CoreData. I have found that this happens every time when I call saveContext(). I don't understand why this happens.

0

There are 0 best solutions below