Just My Life & My Work

[iOS] 包含字串 (Contains String)

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

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


我很自然地就使用它,在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以後可以很開心





WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )


您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.


%d 位部落客按了讚: