简体   繁体   中英

Save multiple Arrays that contain the same Core Data Object

var done = [Item]()
var list = [Item]()

func loadItems() {
    let request: NSFetchRequest<Item> = Item.fetchRequest()
    do {
        list = try context.fetch(request)
    } catch {
        print("Error fetching data from context: \(error)")
    }
    self.tableView.reloadData()
}

func saveItems() {
    do {
        try context.save()
    } catch {
        print("Error saving context: \(error)")
    }
}

When I mark an Item in the list as done I am trying to add it to the done list and delete it from the original list. However, the saveItems() method doesn't save the items in the done list and the loadItems method doesn't load the items for the done list.

When I mark an Item in the list as done I am trying to add it to the done list and delete it from the original list. However, the saveItems() method doesn't save the items in the done list and the loadItems method doesn't load the items for the done list.

There are two ways you could handle this:

  1. Make done a property of Item . Then you can just save all the items without worrying which list they're in. You can fetch the all the items and create your "to do" list by filtering out the items that are marked done, and create the "done" list by filtering out the items that aren't marked done. Fetch requests can be much more sophisticated than just "fetch all the Items." You can instead say "fetch all the items whose done is false."

  2. Fix your code so that the load and save methods do, in fact, load and save both lists, and an item's status continues to depend on which list it's in. Core Data is very good at keeping track of the relationships between objects, so you could easily have an object that has done and todo properties, each of which is a to-many relationship to Item , and marking an item done would just be a matter of moving the item from one set to the other.

To supplement @Caleb's answer, which tells you how to fix this...

The reason this is happening is that those arrays are not saved in Core Data. It doesn't know anything about them, so it can't track which array an object is in. It knows about the objects, but not the arrays. Every time you perform the fetch in your code, you put all the items into list . But it only exists in memory, and never gets saved to Core Data, so the next time around you get the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM