1

I'm noticing when adding items to a List they are out of order. The items are being added using Core Data, in my main View I show a sheet and then a user selects an item it's added to my main List. I assumed the items would be added in some kind of order from first to last.

My main view fetching CoreData items

@FetchRequest(sortDescriptors: [], animation: .default)
private var items: FetchedResults<Items>

List {
    ForEach(items, id: \.self) { item in
        Text(item.city)
    }
}

Core Data saving items in the sheet view.

func addCity(_ city: String) {
    let fetchrequest: NSFetchRequest<Items> = Items.fetchRequest()
    fetchrequest.predicate = NSPredicate(format: "city = %@", city)
    do {
        let items = try viewContext.fetch(fetchrequest)
        if !items.isEmpty {
            presentationMode.wrappedValue.dismiss()
            print("item exists")
        } else {
            let items = Timezone(context: viewContext)
            items.city = city
            try? viewContext.save()
            presentationMode.wrappedValue.dismiss()
        }
    } catch {
        print("error")
    }
}

enter image description here

5
  • Assuming is wrong. You need to handle sorting yourself. Commented Aug 29, 2021 at 6:26
  • Add explicit sort descriptors to have fetched results sorted. Commented Aug 29, 2021 at 6:27
  • I noticed I missed sortDescriptors but I'm unsure how to order it by when it's been added. I used NSSortDescriptor for the key but that just orders it alphabetically. Commented Aug 29, 2021 at 6:28
  • 2
    @cole you need to add a new field to your entity, like creation date, and sort by this field Commented Aug 29, 2021 at 6:45
  • Fixed and working! Commented Aug 29, 2021 at 6:46

1 Answer 1

3

Adding a date key to my Core Data Entity to keep a timestamp worked. And sorting using @FetchRequest(sortDescriptors: [NSSortDescriptor(key: "date", ascending: true)], animation: .default) fixed the issue.

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.