I have an NSArray
in my app. This array consists of custom objects and these custom objects have one NSArray
in that also has these same custom objects. It's structured like this:
@[
entry,
entry,
entry
]
And this Entry
object has a value
parameter that is an NSArray
with entries in it. As you can see it's a nested array of custom objects. However, the value
parameter can be an NSString
as well. My question is: how can I search through this array and search it's children for entries where value is a string and matches the query?
Well, the simplest, and probably not best performing way, is to just loop through them all. Since your data structure seems like it could be arrays of entries, which could have values of arrays of entries, which could go on and on, I would write it as a recursive function.
- (NSArray<Entry *> *)entriesWithValueMatching:(NSString *)value inArray:(NSArray<Entry *> *)arrayOfEntries
{
NSMutableArray *matchingEntries = [NSMutableArray array];
for (Entry *entry in arrayOfEntries) {
if ([entry.value isKindOfClass:[NSArray class]]) {
[matchingEntries addObjectsFromArray:[self entriesWithValueMatching:value inArray:entry.value]];
} else if ([entry.value isKindOfClass:[NSString class]]) {
if ([(NSString *)entry.value isEqualToString:value]) {
[matchingEntries addObject:entry];
}
}
}
return matchingEntries.copy;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.