Irrd Irrd - 3 months ago 11
Objective-C Question

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

Hello I have a

NSMutableDictionary
like this

<__NSArrayM 0x14e226ff0>(
{

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

}


I am adding several objects into my
NSMutablearray
. But I want to check whether this image already available in the
NSMutablearray
. Actually I am planing to search it by the
DocumentName
. How can I check whether that same value is already exists for the
DocumentName
key in the array. I want to add the
NSMutableDictionary
if only its not already exists. This is how I create my
NSMutabledictionary
object.

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


Please help me.
Thanks

Answer

You can try one of these to check image is already exist or not.

1) Using predicate

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

2) Using valueForKey

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