性能问题创建UITableView的部分索引标题

时间:2013-01-07 02:07:14

标签: iphone ios uitableview

我在tableview中显示一个联系人数组([[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];
    }
} 

这很有效,但是当数组很大时它很慢,我确信有更好的方法可以做到这一点,但我对此很新,所以我不确定如何。对于更好的方法有什么建议吗?

2 个答案:

答案 0 :(得分: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];
    }
} 

虽然我不能肯定地说,但我猜想反复访问你的共享商店会让你感到害怕。也许只访问它一次就能满足你的需求。

答案 1 :(得分:0)

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

NSFetchedResultsController将仅加载表视图中可见的行的子集,从而防止用户必须等待对所有联系人进行排序。

NSFetchedResultsController还会按属性(即名字或姓氏)对联系人进行排序,您可以将章节标题设置为您要排序的字段的第一个字母。

请查看此question和此tutorial