在NSArray中检查每个NSDictionary内容的有效方法

时间:2013-09-02 15:19:29

标签: cocoa-touch nsarray nsdictionary

在我的应用程序中,我收到服务器的回复,我必须检查我是否在包含NSArray的{​​{1}}中创建了重复的对象。现在检查对象是否存在我这样做:

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来阻止它。我认为有更好的方法来执行此检查,我想听听您的建议。

2 个答案:

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

但是,正如其他人所说的那样,你可以在一个单独的NSSet中保留一个“摘要”,然后先检查所有词典。

答案 1 :(得分: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
}