I am using the following code
for(NSDictionary* key in [Tags valueForKey:@"data"]) {
if ([[key valueForKey:@"hashtag"] rangeOfString:self.searchKey options:NSCaseInsensitiveSearch].location != NSNotFound) {
NSLog(@"found key");
}
break;
}
For nsdictionary
I do not want to use a for loop to check the first key value if it exists or not. Actually i just want to check if there are hashtags returned in the dictionary or not using only if statement . How is this possible?
CodePudding user response:
You can use a predicate to search for hashtagged tags:
// MARK: - Without Loop
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hashtag != NULL"];
NSArray *hashtaggedTags = [tags filteredArrayUsingPredicate:predicate];
if (hashtaggedTags.count == 0) {
NSLog(@"No hashtags at all");
} else {
NSLog(@"Found some hashtags");
}
Cleaning up your code for a minimum workable code:
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Assuming you have some dictionary like this
NSDictionary * Tags = @{
@"data": @[ // <- Here is the array
@{ // <- here is the dictionary
@"hashtag": @"NightOut",
@"count" : @0,
}
]
};
// Getting the tag value
NSArray* tags = Tags[@"data"];
// MARK: - Without Loop
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hashtag != NULL"];
NSArray *hashtaggedTags = [tags filteredArrayUsingPredicate:predicate];
if (hashtaggedTags.count == 0) {
NSLog(@"No hashtags at all");
} else {
NSLog(@"Found some hashtags");
}
// MARK: - With loop
// Loop through tags (not keys of the dictionary)
for (NSDictionary * tag in tags) {
// Check if `hashtag` is exists and returns something in the dictionary or not
if (tag[@"hashtag"]) {
NSLog(@"There's an object set for key @\"hashtag\"!");
} else {
NSLog(@"No object set for key @\"hashtag\"");
}
}
}
return 0;
}