如何检查NSDictionary中的值是否存在于字典数组中 [英] How to check if the value in an NSDictionary exists in an array of dictionarys

查看:71
本文介绍了如何检查NSDictionary中的值是否存在于字典数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题有点混乱...我会解释

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

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

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.

示例:

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

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

步骤2:在所述视图内按下另一个按钮,以将其某些内容保存到字典中,然后将所述字典添加到数组中.但是,如果已建立的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.

这里有一些我目前无法使用的代码:

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

推荐答案

一种非常简单的检查方法是使用NSPredicate过滤数组.如果没有匹配项,则过滤的结果将是一个空数组.例如:

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:

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

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

这篇关于如何检查NSDictionary中的值是否存在于字典数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆