0

I am using a FetchRequest in a chat app and want to set the fetchLimit dynamically. First I want to load 50 messages, then an additional number when the user scrolls to the top of the chat message list.

I am using the following code:

@FetchRequest private var messages: FetchedResults<Message>

private var predicate: NSPredicate
private var fetchLimit = 50
    
init(chatID: String) {
    
    self.predicate = NSPredicate(format: "chatID_ = %@", chatID)

    self._messages = FetchRequest(
        entity: Message.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Message.createdAt_, ascending: true),
        ],
        predicate: self.predicate
    )
}

How can I incorporate a fetchLimit into this which I can change dynamically?

alionthego
  • 8,508
  • 9
  • 52
  • 125
  • I don’t think you can do that dynamically – Joakim Danielson Nov 06 '21 at 12:13
  • Ok. Thanks. I guess I’ll have to add a date predicate after the object x offset. Which unfortunately means another query to get that object. – alionthego Nov 06 '21 at 12:16
  • 1
    Does this answer your question https://stackoverflow.com/a/61632618/12299030? – Asperi Nov 06 '21 at 13:59
  • Hi @Asperi. It does work very well. It does give me the first 5 rather than the last 5 to preserve the sort order (chat app with most recent message on bottom). That should be trivial to solve by reversing the iteration though. Thanks so much. – alionthego Nov 06 '21 at 14:16

0 Answers0