2014-09-04 132 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