1

在我的应用程序中,我收到了来自服务器的响应,我必须检查我没有在NSArray其中创建重复的对象NSDictionaries。现在要检查对象是否存在,我这样做:

for (int i = 0; i < appDelegate.currentUser.userSiteDetailsArray.count; i++){

   NSDictionary *tmpDictionary = [appDelegate.currentUser.userSiteDetailsArray objectAtIndex:i];

   if ([[tmpDictionary valueForKey:@"webpropID"] isEqualToString:tmpWebproperty.identifier]){
       needToCheck = NO;
   }

   if (i == appDelegate.currentUser.userSiteDetailsArray.count - 1 && ![[tmpDictionary valueForKey:@"webpropID"] isEqualToString:tmpWebproperty.identifier] && needToCheck){
 // It means it's the last object we've iterated through and needToCheck is still = YES;
        //Doing stuff here
     }
  }

我设置了一个BOOL值,因为这个迭代在一个方法中进行了很多次,我不能用return它来停止它。我认为有更好的方法来执行此检查,我想听听您对此的建议。

4

2 回答 2

1
BOOL needToCheck = YES;
for (int i = 0; i < appDelegate.currentUser.userSiteDetailsArray.count; i++){
    NSDictionary *tmpDictionary = [appDelegate.currentUser.userSiteDetailsArray objectAtIndex:i];
    if ([[tmpDictionary valueForKey:@"webpropID"] isEqualToString:tmpWebproperty.identifier]){
        needToCheck = NO;
        break;
    }
 }

 if (needToCheck) {
     //Doing stuff here
 }

But, as others have said, you can maybe keep a "summary" in a separate NSSet that you check first, vs spinning through all the dictionaries.

于 2013-09-02T15:38:52.643 回答
1
NSDictionary *previousThing = nil;
for (NSDictionary *thing in appDelegate.currentUser.userSiteDetailsArray) {
    if ([thing[@"webpropID"] isEqualToString:newWebPropertyIdentifier]) {
        previousThing = thing;
        break;
    }
}

if (previousThing == nil) {
    // no previous thing
} else {
    // duplicate
}
于 2013-09-02T15:58:55.713 回答