Skip to content

Instantly share code, notes, and snippets.

@tomasen
Created April 2, 2020 05:46
Show Gist options
  • Save tomasen/3fcd987921fe30d4e873b5dd95c0e78b to your computer and use it in GitHub Desktop.
Save tomasen/3fcd987921fe30d4e873b5dd95c0e78b to your computer and use it in GitHub Desktop.
Fetch a random row from a CoreData entity
func RandomFetch() -> Item? {
let req = NSFetchRequest<NSFetchRequestResult>(entityName: "MyEntity")
req.predicate = NSPredicate(format: "duedate > %@", due as NSDate)
// find out how many items are there
let totalresults = try! mContext.count(for: req)
if totalresults > 0 {
// randomlize offset
req.fetchOffset = Int.random(in: 0..<totalresults)
req.fetchLimit = 1
let res = try! mContext.fetch(req) as! [Item]
return res.first
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment