如何检查NSDictionary中的值是否存在于字典数组中

时间:2021-04-12 13:44:03

The title is a bit confusing...I'll explain

题目有点让人困惑……我将解释

I have an NSMutableArray I am populating with NSMutableDictionary objects. What I am trying to do is before the dictionary object is added to the array, I need to check whether any of the dictionaries contain a value equal to an id that is already set.

我有一个NSMutableArray,我用NSMutableDictionary对象填充。我要做的是,在将dictionary对象添加到数组之前,我需要检查任何字典是否包含一个值,该值等于已设置的id。

Example:

例子:

Step 1: A button is clicked setting the id of an object for use in establishing a view.

步骤1:单击一个按钮,设置用于建立视图的对象的id。

Step 2: Another button is pressed inside said view to save some of its contents into a dictionary, then add said dictionary to an array. But if the established ID already exists as a value to one of the dictionaries keys, do not insert this dictionary.

步骤2:在上述视图中按下另一个按钮,将其部分内容保存到字典中,然后将该字典添加到数组中。但是,如果已建立的ID已经作为一个字典键的值存在,那么不要插入这个字典。

Here is some code I have that is currently not working:

下面是一些我现在没有使用的代码:

-(IBAction)addToFavorites:(id)sender{
    NSMutableDictionary *fav = [[NSMutableDictionary alloc] init];
    [fav setObject:[NSNumber numberWithInt:anObject.anId] forKey:@"id"];
    [fav setObject:@"w" forKey:@"cat"];

    if ([dataManager.anArray count]==0) {     //Nothing exists, so just add it
        [dataManager.anArray addObject:fav];
    }else {
        for (int i=0; i<[dataManager.anArray count]; i++) {
            if (![[[dataManager.anArray objectAtIndex:i] objectForKey:@"id"] isEqualToNumber:[NSNumber numberWithInt:anObject.anId]]) {
                [dataManager.anArray addObject:fav];
            }       
        }
    }
    [fav release];
}

1 个解决方案

#1


6  

One fairly easy way to do this kind of check is to filter the array using an NSPredicate. If there's no match, the result of filtering will be an empty array. So for example:

进行这种检查的一种相当简单的方法是使用NSPredicate过滤数组。如果没有匹配,过滤的结果将是一个空数组。举个例子:

NSArray *objs = [dataManager anArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", [NSNumber numberWithInt:i]];
NSArray *matchingObjs = [objs filteredArrayUsingPredicate:predicate];

if ([matchingObjs count] == 0)
{
    NSLog(@"No match");
}

#1


6  

One fairly easy way to do this kind of check is to filter the array using an NSPredicate. If there's no match, the result of filtering will be an empty array. So for example:

进行这种检查的一种相当简单的方法是使用NSPredicate过滤数组。如果没有匹配,过滤的结果将是一个空数组。举个例子:

NSArray *objs = [dataManager anArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", [NSNumber numberWithInt:i]];
NSArray *matchingObjs = [objs filteredArrayUsingPredicate:predicate];

if ([matchingObjs count] == 0)
{
    NSLog(@"No match");
}