Search code examples
ioscore-datansmanagedobject

CoreData only saving most recently inserted object


I'm trying to save data associated with pins that are added to a map. Each time a user adds a pin to a map, I want the lat, long, and title of the pin to be saved. Here's my savePin() function:

func savePin(location: BibleLocation) {

    let newPin = NSEntityDescription.insertNewObject(forEntityName: "Pin", into: context!) as! Pin
    newPin.setValue(location.lat, forKey: "lat")
    newPin.setValue(location.long, forKey: "long")
    newPin.setValue(location.name, forKey: "title")
    newPin.setValue(currentBook, forKey: "pinToBook")
    pinsForBook.append(newPin)

    appDelegate.saveContext()

}

The problem is that only the most recent pin inserted is returned by a fetch request:

func getPinsForGlossary() {

    let request: NSFetchRequest<Pin> = Pin.fetchRequest()
    let p = NSPredicate(format: "pinToBook = %@", currentBook!)
    request.predicate = p

    pinsForBook = []
    do {
        let results = try context!.fetch(request as! NSFetchRequest<NSFetchRequestResult>)
        pinsForBook = results as! [Pin]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

I don't think I'm overwriting data when I call insertNewObject. Why is only the most recent inserted object being saved? Thanks in advance.


Solution

  • I guess you have a one-to-one relationship, so when you set currentBook as pinToBook of one object, it is automatically set to nil in the previous one.

    If that's your case, you should set relationship to one-to-many, so that one book can be used in multiple Pin objects as pinToBook value.