How to check if the value in an NSDictionary exists in an array of dictionarys

醉酒当歌 提交于 2021-02-06 13:53:39

问题


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.

Example:

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

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

回答1:


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");
}


来源:https://stackoverflow.com/questions/3710094/how-to-check-if-the-value-in-an-nsdictionary-exists-in-an-array-of-dictionarys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!