简体   繁体   English

如何使用嵌套数组搜索自定义对象的NSArray?

[英]How to search NSArray of custom objects with nested arrays?

I have an NSArray in my app. 我的应用程序中有一个NSArray This array consists of custom objects and these custom objects have one NSArray in that also has these same custom objects. 该数组由自定义对象组成,这些自定义对象具有一个NSArray ,该NSArray也具有这些相同的自定义对象。 It's structured like this: 它的结构如下:

@[
    entry,
    entry,
    entry
]

And this Entry object has a value parameter that is an NSArray with entries in it. 并且此Entry对象具有一个value参数,该参数是其中包含条目的NSArray As you can see it's a nested array of custom objects. 如您所见,它是一个嵌套的自定义对象数组。 However, the value parameter can be an NSString as well. 但是, value参数也可以是NSString 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM