多次获得相同的联系人而不是多个联系人

时间:2013-08-23 11:46:44

标签: ios objective-c uitableview data-structures abaddressbook

您好我是iphone应用程序开发的新手,但这个问题更多的是编码相关。我正在使用tableview来显示用户名(textLabel)和phoneNumbers(detailtextLabel)当然使用Addressbook。我已将它们存储在单独的数组中。另外,我有一个存储在单独数组中的电子邮件地址。并使用所有这些我成功地能够在创建的表视图中按排序顺序显示联系人。问题出现在searchDisplayController的实现中。在这里,我希望能够按用户名称和emailid(或者)进行搜索。

所以,我使用NSDictionary将名称+电子邮件存储为值(NSString格式),其中键作为显示该联系人的行的索引。现在,我使用以下代码成功获取所有匹配联系人的数组。

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{

NSPredicate *resultPredicate = [NSPredicate
                                predicateWithFormat:@"SELF contains[cd] %@",
                                searchText];

searchResults  = nil;
matchingContacts = nil;
NSArray *allContactValues = [allContactNamesWithEmailIDs allValues];
searchResults = (__bridge CFArrayRef)([[allContactValues sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] filteredArrayUsingPredicate:resultPredicate]);
matchingContacts  = [[NSMutableArray alloc] initWithArray:(__bridge NSMutableArray*)searchResults];

matchingContacts返回所有匹配联系人姓名的数组。所有 但是当有两个用户具有相同的名称(相同的值,不同的键)时,使用它有一个缺点,我无法将其追溯到不同的键。它显示相同的名称和相同的phoneNumbers两次,这将是一个问题。

创建单元格的代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{     static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

}
    if(tableView == self.searchDisplayController.searchResultsTableView){

        if (farmMarkets.count>0) {
            destIndex = [[[allContactNamesWithEmailID allValues] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)] indexOfObject:matchingContacts[indexPath.row]];  //?? I believe this is what needs to be modified to display multiple contacts. Just don't know how.

            [cell.textLabel setText:farmMarkets[destIndex]];

            if (destIndex<0) {
                [cell.detailTextLabel setText:@""];
            }
            else{
                [cell.detailTextLabel setText:phoneNumbersArray[destIndex]];
            }

        }
    }

}

有人可以给我一个代码示例,解释如何更好地实现这一点吗?所有想法都会有所帮助。总之,我现在将总结一下。我想实现一个tableView,显示名称和电话号码的联系人以及顶部的搜索栏。当我使用姓名或电子邮件ID进行搜索时,它应显示带有相应电话号码的姓名。

1 个答案:

答案 0 :(得分:0)

根据您的描述,您有许多不同的存储数据的方法,并且您的问题来自于尝试在不同时间将它们关联在一起。

我会简化你的结构,所以你有一个单一的源信息数组,其中该数组包含字典。每个字典都包含一个人的所有数据。

现在,您可以根据需要和字典中的任何(组合)键对该数组进行排序。此外,当您过滤时,您可以过滤数组(或者更好的是,它的副本,因此您仍然拥有原始数据),因此维护顺序,您不需要与其他任何内容相关联。