关于ios:在核心数据中搜索最接近的值 | 珊瑚贝

Search core data for closest value


目前我们有一个包含多个 r、g、b 值的数据库,这些值被拆分为自己的属性。例如:

1
2
3
 r = type float
 g = type float
 b = type float

每个 r、g 和 b 属性将有多个值。
从外部来源获取浮点数后,我们希望搜索数据库以返回与该浮点数最接近的属性。 (例如,对于 r,如果我们得到一个 199 的值,将返回与 199 最接近的 r 值)。

我知道有一些谓词可以像这样使用:”text CONTAINS %@”,但我没有看到任何用于 \\’closest value\\’ 的谓词。

  • 您必须定义您的术语 closest 的某个范围。对我来说,最接近的 199 可能是 220,但对其他人来说不是最接近的。您对此有任何阈值吗?
  • @UmairAamir 没有阈值,它只需要获取最接近的值。数据库包含数千个值,r,g,b


您可以在请求中使用 NSSortDescriptor(key:”name_key”, ascending: true)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

那么你可以使用两次predicate:

第一次使用格式 text < %@ 并使用数组的最后一项。

第二次使用 text > %@ 格式并使用数组的第一项。

将两次迭代中的第一项和最后一项的差异与您的给定值进行比较,看看谁的差异更小。这将是最接近的值。

如果你不知道如何从核心数据中获取数据,你可以关注 Fetching Objects

核心数据入门

  • 您可以使用谓词搜索排序描述符吗?
  • “搜索排序描述符”?基本上 predicates 和 sort descriptors 与 fetch requests 合并。不知道你是怎么做的。
  • 我认为我对您的答案并不完全清楚,您将如何使用谓词两次?
  • 好的,所以要在最后找到最接近的数字: if request1 > request2 { r = request1}
  • name_key 是什么,它与问题中提到的数字 RGB 值有什么关系?
  • 它是属性名称。在此基础上,您将对数据进行排序。例如,如果您想根据 r 进行排序,那么您将通过 r 而不是 name_key


来源:https://www.codenong.com/48289415/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9951.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?