浮點數不許,這個貌似基本都知道。可是在開發中不少人沒有對它的使用產生警覺。若是你在開發iOS應用,你可能使用過以下代碼判斷系統版本: ios
|
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { //something support for ios7 } |
這樣一段代碼也的確工做良好,可是注意了若是你把比較的數值改成7.1,那麼頗有可能就會出問題。 學習
浮點數不許
這一篇博文從二進制的表示方面說明了爲何浮點數不許,講的很好,感興趣的能夠學習學習,學習這些感受仍是頗有用的,也能夠幫助咱們定位一些詭異的問題。 spa
在精確的比較中不要使用float
文章開頭的系統版本的比較就是一個典型的例子,咱們能夠經過其餘方法實現比較: code
|
if ([[[UIDevice currentDevice] systemVersion] compare:@"7.1"] != NSOrderedAscending) { //something support for ios7 } |
- NSString 兩個字符串的比較,用 a compare:b 來比,得出的結果分3種
-
- 1. 26個字母比較 越靠後面 越大
- NSString *a = @"qweqwe";
- NSString *b = @"qweasd";
- BOOL result = [a compare:b];
- if (result == NSOrderedSame) { // NSOrderedSame = 0 徹底同樣
- NSLog(@"a = b");
- }else if(result == NSOrderedAscending) // NSOrderedAscending = -1
- NSLog(@"a < b");
- else{ //NSOrderedDescending = +1
- NSLog(@"a > b");
- }
-
- 2011-07-05 15:04:33.951 Q[5180:207] a > b
-
- 2.比較數字或者符號,或者字母 什麼都行
-
- NSString *a = @"1.0.30qweqwe";
- NSString *b = @"1.0.45qweasd";
- BOOL result = [a compare:b];
- if (result == NSOrderedSame) { // NSOrderedSame = 0 徹底同樣
- NSLog(@"a = b");
- }else if(result == NSOrderedAscending) // NSOrderedAscending = -1
- NSLog(@"a < b");
- else{ //NSOrderedDescending = +1
- NSLog(@"a > b");
- }
-
- 2011-07-05 15:05:13.175 Q[5209:207] a < b
-
- 3.不考慮大小寫比較字符串
- [a caseInsensitiveCompare:b]
-
-
-
- - (void)viewDidLoad
- {
- NSString *a = @"i love my boyfriend.";
- NSString *b = @"I Love My Boyfriend.";
- NSLog(@" \n a: %@ \n",a);
- NSLog(@" \n b: %@ \n",a);
- BOOL result = [a caseInsensitiveCompare:b] == NSOrderedSame;
- }
- // result = (BOOL) YES;
-
- 4.不考慮大小寫比較字符串
- [a caseInsensitiveCompare:b]
-
- - (void)viewDidLoad
- {
- NSString *a = @"i love my boyfriend.";
- NSString *b = @"Little baby.";
- NSLog(@" \n a: %@ \n",a);
- NSLog(@" \n b: %@ \n",a);
- BOOL result = [a caseInsensitiveCompare:b] == NSOrderedAscending;
- }
- //result = (BOOL) YES;
-
-
- 5. 有選擇的比較大小 [a compare:b options:NSCaseInsensitiveSearch|NSNumericSearch]
- - (void)viewDidLoad
- {
- NSString *a = @"i love my boyfriend.";
- NSString *b = @"I Love My Boyfriend.";
- NSLog(@" \n a: %@ \n",a);
- NSLog(@" \n b: %@ \n",b);
- BOOL result = [a compare:b options:NSCaseInsensitiveSearch|NSNumericSearch] == NSOrderedSame;
- }
- //result = (BOOL)YES;
- NSCaseInsensitiveSearch 忽略大小寫的比較字符串
- NSNumericSearch 比較字符串的個數
- NSLiteralSearch 區分大小寫,進行徹底比較