I have an NSArray
called groups
containing NSArray
objects which each contain QuestionSub
objects, which in its turn inherit from the Question
class.
The Question class consist of, amongst others, an NSString
value called Id
. This is the string I would like to search for.
The problem is that QuestionSub
contains an NSString
called parent
, which is a reference to a parent Question; hence I cannot use an NSPredicate
with query the ANY
statement since it will match on any equal string.
My problem is that my search doesn't return a result. However, I can't seem to find the right query for my NSPredicate
to get a correct result.
This is my code:
/**
* Get the (QuestionSub)[QuestionSub] for a questuon GUID
*
* @param guid NSString The GUID of the question
*
* @return QuestionSub The QuestionSub
*/
- (QuestionSub *)getQuestionForGuid:(NSString *)guid
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Id == %@", guid];
NSArray *filtered = [self.groups filteredArrayUsingPredicate:predicate];
if (filtered.count > 0)
{
return [filtered objectAtIndex:0];
}
else {
return nil;
}
}
This is a representation of my NSArray
:
The problem is that filteredArrayUsingPredicate: filters the entire groups array. So ANY operator says to filter out all subarrays which contain Question object with needed Id property.
In your Example you have Questions with the same Id and parent in the same subarray, so ANY works here properly and there is no difference between == and CONTAINS for our goal.
To get needed result you first need to flatten your groups to one-dimensional array of Questions and then apply your predicate.
Unfortunately NSArray class does't provide any method to flatten multi-dimensional array (: