2010-01-08 40 views
14

我的託管對象有兩個雙字段:「緯度」,「經度」。 我需要獲取的所有對象,具有一定的座標NSPredicate不使用double值(%f)?

此代碼不能正常工作,fetchedObjects數= 0

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude == %f AND longitude == %f", coordinate.latitude, coordinate.longitude]; 

但這個代碼做工精細,fetchedObjects數= 3:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude == 53.012667 AND longitude == 36.113000"]; 

回答

25

它適用於很長時間的浮動,%lf

+0

接受你的答案是正確的,如果它解決您的問題 – Vladimir 2010-01-08 09:56:36

+3

作爲jdeprez說你不應該比較浮點值。比較浮點值是危險且不好的做法。相反,使用相當大的區域作爲謂詞,然後計算從距離返回對象數組中最近的點到距離搜索點的距離。 – Christopher 2012-07-16 23:53:39

+0

您節省了我的一天..... :-) – 2016-12-28 07:24:06

14

哎呀...

請不要使用==比較浮點值。

如果要查找具有「特定」值的對象,請在小範圍內進行比較。否則,浮點表示錯誤會咬你。

所以考慮使用:

const float epsilon = 0.000001; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude > %f AND latitude < %f AND longitude > %f AND longitude < %f", coordinate.latitude - epsilon, coordinate.latitude + epsilon, coordinate.longitude - epsilon, coordinate.longitude + epsilon]; 
+1

Clang's ** float.h **定義了一些與浮點數和雙精度相關的常量。其中兩個是'FLT_EPSILON'(1E-5)和'DBL_EPSILON'(1E-9),應該用這個來代替這裏給出的εE-6。這些常數的特徵由[C99 5.2.4.2.2](http://c0x.coding-guidelines.com/5.2.4.2.2.html)定義。 – 2015-01-13 18:48:17

+1

如果你對雙精度進行比較,使用'%lf' – ken 2016-04-28 02:46:08

2

這是因爲浮動的精確度不是100%。所以,你也可以這樣做:

[NSPredicate predicateWithFormat:@"abs(latitude - %f) < 0.0001 AND abs(longitude - %f) < 0.0001", coordinate.latitude, coordinate.longitude] 
+0

我得到這個錯誤信息:'''無效謂詞',原因:''abs:'函數不被支持。'''' – 2016-09-14 11:52:23

0

使用該轉換到的NSNumber:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude == %@ AND longitude == %@", @(coordinate.latitude), @(coordinate.longitude)];