Created
April 2, 2020 05:46
-
-
Save tomasen/3fcd987921fe30d4e873b5dd95c0e78b to your computer and use it in GitHub Desktop.
Fetch a random row from a CoreData entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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