2014-09-04 130 views
0

我工作的自定義聯繫人,我目前使用此代碼搜索自定義對象搜索自定義對象

filteredTableData = [[NSMutableArray alloc] init]; 
    for (int i=0; i<contactSectionTitles.count; i++) 
    { 
     NSString *sectionTitle = [contactSectionTitles objectAtIndex:i]; 
     NSArray *sectionmContacts = [mContacts objectForKey:sectionTitle]; 
     for (CS_ContactDTO *theDto in sectionmContacts) { 
      NSRange nameRange = [theDto.mFirstName rangeOfString:text options:NSForcedOrderingSearch]; 
      NSRange descriptionRange = [[theDto.mFirstName description] rangeOfString:text options:NSForcedOrderingSearch]; 
      if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound) 
      { 
       if (![filteredTableData containsObject:theDto])//Search DTO 
       { 
        [filteredTableData addObject:theDto]; 
       } 
      } 
     } 
    } 

注意 「theDTO」是我的自定義類
它值FirstName,LastName,PhoneNumber。

代碼給我造成像,
對於「A」 - >「阿倫」,「印度」,「庫瑪」
我的要求是要搜索
「A」只提供「阿朗」(開始字母匹配),而不是其他結果。

+0

聽不懂你的要求,你要搜索'name'或'description'與開始搜索字符串? – bhargavg 2014-09-04 15:34:38

+0

我需要搜索名字。 – 2014-09-04 15:36:30

回答

2

簡單地改變你的檢查,以查看該範圍位置爲0:

if (nameRange.location == 0 || descriptionRange.location == 0) { 

如果text是在名稱或說明的開始這會成真。

順便說一句 - 爲什麼你檢查mFirstNamemFirstName description?有什麼不同?

+0

我正在趁機(擊中n試用)來獲得理想的結果。 – 2014-09-04 15:38:13

+1

你不應該依賴'description'方法的輸出。它只能用於調試。 – rmaddy 2014-09-04 15:38:56

+0

我不知道,謝謝 – 2014-09-04 15:40:25

1

如果你想檢查是否NSString與特定search學期開始,你可以使用

if ([myString hasPrefix:@"searchTerm"]) 
+0

這適用於簡單的情況。使用'rangeOfString:options:'提供了更多的選項,如case和diacritic insensitive match。 – rmaddy 2014-09-04 15:40:21

+0

@rmaddy,我同意,因爲OP只是想檢查字符串是否以搜索字詞開頭,所以我提出了這個方法。 – bhargavg 2014-09-04 15:41:29

+0

+1表示這個,這對我來說是新的 – 2014-09-04 15:45:59