我正在尝试制作一款可以检测重复联系人的iPhone应用。我已经做了一个for循环来循环遍历所有联系人(人)的数组,但它似乎只工作一次。
for (int i = 0; i < [people count]; i++)
{
ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
ABRecordRef person2;
NSString *firstname = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSLog(@"Firstname = %@", firstname);
NSLog(@"People count = %i", [people count]);
for (int j = 0; i < [people count]; i++)
{
person2 = (ABRecordRef)[people objectAtIndex:i];
if (j != i
&& [firstname isEqualToString:(NSString*)ABRecordCopyValue(person2, kABPersonFirstNameProperty)]
&& [lastname isEqualToString:(NSString*)ABRecordCopyValue(person2, kABPersonLastNameProperty)])
{
//duplicate is found
NSString *name = firstname;
name = [name stringByAppendingString:@" "];
name = [name stringByAppendingString:lastname];
[duplicates addObject:name];
}
}
}
NSLog(@"Exited loop!");
NSLog的输出是:
Firstname = Bob
People count = 3
Exited loop!
我尝试用[people count]代替3,但输出相同。我没有休息;在我的代码中的任何地方声明,所以我不知道问题是什么......
答案 0 :(得分:1)
您正在测试并递增内循环中的i
变量;它应该是j
:
for (int j = 0; j < [people count]; j++)
当像这样循环时,我通常使用另一种for-style循环:
for (Person *p in peopleArray) {
// do something amazing here with p.
}
答案 1 :(得分:1)
您正在测试并在内循环中递增i
。
此外,内环应仅测试小于(或者大于)i的j的值。目前,您正在测试每对两次。
int n = [people count]; // minor perf improvement
for (int i = 1; i < n; ++i) {
...
for (int j = 0; j < i; ++j) {
...
这也避免了j != i
测试。
为了进一步改进,而不是内循环,将人名添加到NSSet
并测试该集的成员身份以识别重复项。对于大量人群来说,这要快得多。
答案 2 :(得分:1)
是的,for (int j = 0; i < [people count]; i++)
这是我们所犯的错误,比我们想承认的更多。