0

我在表格视图中显示一组联系人( [[ContactStore sharedStore]allContacts] ),并将列表划分为字母部分。我使用以下代码返回联系人首字母的数组,以及每个字母条目数的字典。

    //create an array of the first letters of the names in the sharedStore
nameIndex = [[NSMutableArray alloc] init];

//create a dictionary to save the number of names for each first letter
nameIndexCount = [[NSMutableDictionary alloc]init];

for (int i=0; i<[[[ContactStore sharedStore]allContacts]count]; i++){

//Get the first letter and the name of each person
    Contact *p = [[[ContactStore sharedStore]allContacts]objectAtIndex:i];
    NSString *lastName = [p lastName];
    NSString *alphabet = [lastName substringToIndex:1];


    //If that letter is absent from the dictionary then add it and set its value as 1 
    if ([nameIndexCount objectForKey:alphabet] == nil) {
        [nameIndex addObject:alphabet];
        [nameIndexCount setValue:@"1" forKey:alphabet];
    //If its already present add one to its value
    } else {

        NSString *newValue = [NSString stringWithFormat:@"%d", ([[nameIndexCount valueForKey:alphabet] intValue] + 1)];

        [nameIndexCount setValue:newValue forKey:alphabet];
    }
} 

这可行,但是当数组很大时它非常慢,我确信有更好的方法可以做到这一点,但我对此很陌生,所以不知道如何。有没有更好的方法来做到这一点?

4

2 回答 2

2

尽管 Bio Cho 有一个很好的观点,但您可能会看到通过调用

[[ContactStore sharedStore]allContacts]

只有一次。例如:

nameIndex = [[NSMutableArray alloc] init];
nameIndexCount = [[NSMutableDictionary alloc] init];

/*
 Create our own copy of the contacts only once and reuse it
 */
NSArray* allContacts = [[ContactStore sharedStore] allContacts];

for (int i=0; i<[allContacts count]; i++){
    //Get the first letter and the name of each person
    Contact *p = allContacts[i];
    NSString *lastName = [p lastName];
    NSString *alphabet = [lastName substringToIndex:1];

    //If that letter is absent from the dictionary then add it and set its value as 1 
    if ([nameIndexCount objectForKey:alphabet] == nil) {
        [nameIndex addObject:alphabet];
        [nameIndexCount setValue:@"1" forKey:alphabet];
    //If its already present add one to its value
    } else {
        NSString *newValue = [NSString stringWithFormat:@"%d", ([[nameIndexCount 
            valueForKey:alphabet] intValue] + 1)];

        [nameIndexCount setValue:newValue forKey:alphabet];
    }
} 

虽然我不能肯定地说,但我猜反复访问您的共享商店是杀死您的原因。也许只访问一次就会给你你需要的东西。

于 2013-01-07T02:42:31.827 回答
0

考虑将联系人存储在 Core Data 中并使用 NSFetchedResultsController。

NSFetchedResultsController 只会加载表格视图中可见的行的子集,从而防止您的用户必须等待所有联系人被排序。

NSFetchedResultsController 还将按属性(即名字或姓氏)对您的联系人进行排序,并且您可以将部分标题设置为您正在排序的字段的第一个字母。

看看这个问题和这个教程

于 2013-01-07T02:30:36.443 回答