在iOS中搜索自定义对象

时间:2014-09-04 15:31:19

标签: ios ios7 range nspredicate

我正在处理自定义联系人,目前我正在使用此代码搜索自定义对象

    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];
                }
            }
        }
    }

注意 &#34; theDTO&#34;是我的自定义班级 它具有值FirstName,LastName,PhoneNumber。

代码给我的结果像,
对于&#34; A&#34; - &GT; &#34;阿伦&#34;&#34;印度&#34;&#34;库马尔&#34; 我的要求就是搜索 &#34; A&#34;应该只提供&#34; Arun&#34;(开始字母匹配),而不是其他结果。

2 个答案:

答案 0 :(得分:2)

只需更改您的支票,查看范围位置是否为0:

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

如果text位于名称或说明的开头,则会出现这种情况。

顺便说一句 - 为什么同时检查mFirstNamemFirstName description?有什么区别?

答案 1 :(得分:1)

如果您想检查NSString是否以特定search字词开头,可以使用

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