gpt4 book ai didi

iphone - 为 UITableView 创建节索引标题的性能问题

转载 作者:行者123 更新时间:2023-11-28 22:42:15 27 4
gpt4 key购买 nike

我在表格 View 中显示联系人数组 ( [[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];
}
}

这行得通,但是当数组很大时速度很慢,我相信有更好的方法可以做到这一点,但我对此很陌生,所以不确定如何做。是否有更好的方法来执行此操作的建议?

最佳答案

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

虽然我不能肯定地说,但我猜重复访问您的共享商店是让您丧命的原因。也许只需访问一次就可以满足您的需求。

关于iphone - 为 UITableView 创建节索引标题的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14188945/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com