如何在 NSMutableDictionaries 的 NSMutableArray 中搜索特定键的值?

How to search a value for a particular key in NSMutableArray of NSMutableDictionaries?

你好,我有一个NSMutableDictionary这样的

<__NSArrayM 0x14e226ff0>(
{

DocumentName = "IMG_2597.JPG";
DocumentType = JPG;
Image = "<UIImage: 0x14e52c370> size {1239, 1242} orientation 0 scale 1.000000";

}

我正在向 NSMutablearray 添加几个对象。但我想检查此图像是否已在 NSMutablearray 中可用。其实我打算按 DocumentName 搜索它。如何检查数组中的 DocumentName 键是否已经存在相同的值。如果 NSMutableDictionary 尚不存在,我想添加它。这就是我创建 NSMutabledictionary 对象的方式。

NSMutableDictionary *imageDictionary=[[NSMutableDictionary alloc] init];
[imageDictionary setObject:chosenImage forKey:@"Image"];
[imageDictionary setValue:strDocNAme forKey:@"DocumentName"];
[imageDictionary setValue:strExtension forKey:@"DocumentType"];
[mutarrayImages addObject:imageDictionary];

请帮助我。 谢谢

您可以尝试其中之一来检查图像是否已经存在。

1) 使用谓词

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DocumentName = 'IMG_2597.JPG'"];
NSArray *arr = [yourArray filteredArrayUsingPredicate:predicate];
if (arr.count > 0) {
    NSLog(@"Object is contain");
}

2) 使用 valueForKey

NSArray *documentName = [yourArray valueForKey:@"DocumentName"];
if ([documentName containsObject:@"IMG_2597.JPG"]) {
     NSLog(@"Object is contain");
}
  NSArray *allObjectsArray;  // your array

NSMutableArray *resultObjectsArray = [NSMutableArray array];
for(NSDictionary *dict in allObjectsArray)
{
    NSString *docName = [dict objectForKey:@"DocumentName"];
    NSRange range = [docName rangeOfString:@"your string which you want to match" options:NSCaseInsensitiveSearch];
    if(range.location != NSNotFound)
        [resultObjectsArray addObject:dict];
}
NSSet* myValuesSet = [NSSet setWithArray: [mutarrayImages valueForKey:@"DocumentName"]];
if ([[myValuesSet allObjects] containsObject:< DocumentName to compare >]) {
    NSLog(@"Exist");
}
else{
    NSLog(@"Does not exist");
}