cole
cole

Reputation: 1273

SwiftUI - List order

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

Upvotes: 1

Views: 1018

Answers (1)

cole
cole

Reputation: 1273

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.

Upvotes: 3

Related Questions