UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

fetchLimit doesn't work when adding new records in @FetchRequest

Forums > SwiftUI

When I add new records they will appear in List regardless fetchLimit for @FetchRequest. How to fix it?

@FetchRequest(fetchRequest: Item.fetchRequestLimit(fetchLimit: 2))
    private var items: FetchedResults<Item>

var body: some View {
    VStack {
        Button(action: addItem) {
            Label("Add Item", systemImage: "plus")
        }

        List {
            ForEach(items) { item in
                Text("Item at \(item.timestamp!, formatter: itemFormatter)")
            }
        }
    }
}

private func addItem() {
    withAnimation {
        let newItem = Item(context: viewContext)
        newItem.timestamp = Date()

        PersistenceController.shared.save()
    }
}

extension Item {
    static func fetchRequestLimit(fetchLimit: Int) -> NSFetchRequest<Item> {
        let request: NSFetchRequest<Item> = Item.fetchRequest()

        request.fetchLimit = fetchLimit
        request.sortDescriptors = [NSSortDescriptor(keyPath: \Item.timestamp, ascending: false)]

        return request
    }
}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.