Search code examples
iosswiftcore-datanspredicate

Search core data for closest value


Currently we have a database of multiple values for r,g,b, split into own attributes. ex:

 r = type float
 g = type float
 b = type float

There will be multiple values for each r, g, and b attribute. After getting a float from an outside source, we want to search the database to return the attribute with the closest number to that float. (ex. for r, if we get a value of 199, the r value with the closest value to 199 will be returned).

I know there are predicates that can be used like: "text CONTAINS[c] %@" but I didn't see any predicates for 'closest value'.


Solution

  • You can use NSSortDescriptor(key: "name_key", ascending: true) with your request.

    let request1 = NSFetchRequest<NSFetchRequestResult>() // use correct constructor
    let sortDescriptor = NSSortDescriptor(key: "name_key", ascending: true)
    let sortDescriptors = [sortDescriptor]
    request1.sortDescriptors = sortDescriptors
    
    let predicate1 = NSPredicate(format: "text < %@", value)
    request1.predicate = predicate1
    // use this request1 to fetch from core data
    
    let request2 = NSFetchRequest<NSFetchRequestResult>() // use correct constructor
    request2.sortDescriptors = sortDescriptors
    
    let predicate2 = NSPredicate(format: "text > %@", value)
    request2.predicate = predicate2
    // use this requst2 to fetch from core data
    

    Then you can use predicate twice:

    First time with format text < %@ and use last item of the array.

    and

    Second time with format text > %@ and use the first item of the array.

    compare the difference of your first and last items from both iterations with your given value and see whose difference is smaller. That will be closest value.

    If you don't know how to fetch data from core data you can follow Fetching Objects

    Getting started with core data