Search code examples
iosuitableviewcore-datansfetchedresultscontroller

Core Data: Fetching 'Rows' Before a Given Set of 'Rows'


I have a NSFetchedResultsController that gets me a collection of 'transaction'-esque objects that match a certain criteria — a sale over $100, for example. Each transaction has a unique integer identifier that corresponds to the relative time of the transaction (transaction 23 came before transaction 24). I have no problem displaying the results in a UITableView Controller. What I'd like to do is also show the transaction that occurred right before each of these sales over $100, i.e.:

Transaction - $93 (id = 1)

Transaction - $101 (id = 2)

Transaction - $12 (id = 13)

Transaction - $243 (id = 14) etc.

and then display this list of results in a TableView. There is no chance that two transactions over $100 happened after one another so there is no worry about duplicated entries. Is there any way to do this? I was searching around on how to do this in SQL for inspiration, but there were only answers on how to get 'rows' immediately before a given individual result row, not a set of them.

Any ideas?


Solution

  • You can do it with two fetches and one sorting operation (short of fetching all transactions and filtering in memory).

    First fetch all transactions above 100$. Then extract the ids and fetch the corresponding preceding transactions. Merge and sort.

    // first fetch with this predicate
    NSPredicate(format:"amount > 100")
    
    // get all previous ids
    let previousIDs = result.map { $0.id - 1 }
    
    // fetch the other records with this predicate
    NSPredicate(format:"id in %@", previousIDs)
    
    // merge & sort
    let finalResult = (result + result2).sort { $0.id < $1.id }