Just My Life & My Work

Posts tagged ‘string’

[iOS] 謂詞不區分大小寫 (Predicate for Case-Insensitive)

處理字串真的是一門大學問,這次我想要搜尋某個關鍵字,是英文且不區分大小寫,此時我可以怎麼做?

我們可以使用Predicate設定Case-Insensitive,翻譯成中文是謂詞不區分大小寫,真是彆扭啊~

Apple官方文件有段描述:

String comparisons are by default case and diacritic sensitive. You can modify an operator using the key characters c and d within square braces to specify case and diacritic insensitivity respectively, for example firstName BEGINSWITH[cd] $FIRST_NAME.

意思就是只要在Predicate中加入[cd],就能找到英文不區分大小寫的字串囉~

(繼續閱讀…)

[iOS] 包含字串 (Contains String)

程式語言會隨著時間進化。本次專案依然會處理字串,我自己定義字串來區別用途,想知道是否包含字串 (Contains String),iOS 7以前的作法很拐彎抹角,我是查詢StackOverflow才知道,而且不是查詢一次就記起來,可見這支NSString的method有多不直覺!

iOS 8以後,就可以用「包含」這個方法:

containsString

我很自然地就使用它,在iPhone 6/6+跑都沒問題,因為一買來就是iOS 8。直到夥伴大鳥跟我說,用它iPhone 5一跑就崩潰,後來得知它手機還是iOS 7,就在想是那支method有問題。答案揭曉⋯⋯

/**
 Theme: Contains String
 IDE: Xcode 6
 Language: Objective C
 Date: 104/03/31
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
/* containsString: returns YES if the target string is contained within the receiver. Same as calling rangeOfString:options: with no options, thus doing a case-sensitive, non-literal search. localizedCaseInsensitiveContainsString: is the case-insensitive variant. Note that it takes the current locale into effect as well.  Locale-independent case-insensitive operation, and other needs can be achieved by calling rangeOfString:options:range:locale: directly.
 */
- (BOOL)containsString:(NSString *)aString NS_AVAILABLE(10_10, 8_0);

//--

/* These methods return length==0 if the target string is not found. So, to check for containment: ([str rangeOfString:@"target"].length > 0).  Note that the length of the range returned by these methods might be different than the length of the target string, due composed characters and such.
*/
- (NSRange)rangeOfString:(NSString *)aString;

//--

    NSString *str;
    if ([str rangeOfString:@"HappyDay"].location != NSNotFound) {
        // iOS 7以前拐彎抹角
    }

    if ([str containsString:@"HappyDay"]) {
        // iOS 8以後可以很開心
    }

把method的名稱設計得很直覺,真的是件好事呀~

參考:。

[iOS] NSDate

原本以為獲取日期和時間的方法很簡單,沒想到它是如此深奧,我查詢一些跟NSDate相關的API用法,只要掌握幾個簡單的原則,就可運用自如。像是由 NSDate 轉換為 NSString,和由 NSString 轉換為 NSDate

(繼續閱讀…)

標籤雲

%d 位部落客按了讚: