Reputation: 132
What I am trying to achieve is to search an array for a string, here is the code for searching the array
if ([EssentialsArray containsObject:imageFilePath]) {
NSLog(@"YES");
}
else {
NSLog(@"NO");
NSLog(@"%@", ImageFilePath);
NSLog(@"%@", EssentialsArray);
}
The NSLogs return this for the imageFilePath:
/var/mobile/Applications/5051DC84-CAC8-4C1D-841D-5539A1E28CB1/Documents/12242012_11025125_image.jpg
And this for the EssentialsArray:
(
{
EssentialImage = "/var/mobile/Applications/5051DC84-CAC8-4C1D-841D-5539A1E28CB1/Documents/12242012_11025125_image.jpg";
}
)
And then obviously they return a "NO" value because the array couldn't find the string. Thanks in advance
Upvotes: 1
Views: 2436
Reputation: 438467
The issue is that the invocation of [EssentialsArray containsObject:imageFilePath]
clearly assumes that EssentialsArray
is an array of strings, whereas it's not. It's an array of dictionary entries with one key, EssentialImage
.
There are at least two solutions. The first is to make an array of strings for those dictionary entries whose key is EssentialImage
:
NSArray *essentialImages = [essentialsArray valueForKey:@"EssentialImage"];
if ([essentialImages containsObject:imagePath])
NSLog(@"YES");
else
NSLog(@"NO");
Depending upon the size of your essentialsArray
(please note, convention dictates that variables always start with a lower case letter), this seems a little wasteful to create an array just so you can do containsObject
, but it works.
Second, and better in my opinion is to use fast enumeration to go through your array of dictionary entries, looking for a match. To do this, define a method:
- (BOOL)arrayOfDictionaries:(NSArray *)array
hasDictionaryWithKey:(id)key
andStringValue:(NSString *)value
{
for (NSDictionary *dictionary in array) {
if ([dictionary[key] isEqualToString:value]) {
return YES;
}
}
return NO;
}
You can now check to see if your array of dictionaries has a key called @"EssentialImage"
with a string value equal to the string contained by imagePath
if ([self arrayOfDictionaries:essentialsArray
hasDictionaryWithKey:@"EssentialImage"
andStringValue:imagePath])
NSLog(@"YES");
else
NSLog(@"NO");
Update:
You can also use predicates:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"EssentialImage contains %@", imagePath];
BOOL found = [predicate evaluateWithObject:array];
Upvotes: 4