3

假设我有 2 个NSDictionaries我事先不知道的,例如:

NSDictionary *dictA = @{ @"key1" : @1,
                         @"key2" : @2  };

NSDictionary *dictB = @{ @"key1" : @"a string" };

我想找到 的键dictB和 的键或值之间的第一个匹配项dictA。的每个键dictB要么是一个 NSNumber 要么是一个字符串。如果是数字,请尝试从 的中查找匹配项dictA。如果是字符串,请尝试dictA.

使用 for 循环,它看起来像这样:

id match;
for (id key in dictA ) {
    for (id _key in dictB {
        if ( [_key is kindOfClass:NSNumber.class] && _key == dictA[key] ) {
            match = _key
            goto outer;
        }
        else if ( [_key is kindOfClass:NSString.class] && [_key isEqualToString:key] ) {
            match = _key
            goto outer;
        }
    }
};
outer:;

NSString *message = match ? @"A match was found" : @"No match was found";
NSLog(message);

我如何使用RACSequenceRACStream方法用 ReactiveCocoa 重写它,所以它看起来像:

// shortened pseudo code:
// id match = [dictA.rac_sequence compare with dictB.rac_sequence using block and return first match];
4

1 回答 1

4

您基本上想创建字典的笛卡尔积并对其进行选择。我知道 ReactiveCocoa 中没有默认运算符可以为您执行此操作。(在 LINQ 中有用于此操作的运算符。)在 RAC 中,最简单的解决方案是使用scanWithStart:combine:方法来实现此操作。一旦笛卡尔准备好了,filter:andtake:1操作将产生您选择的序列。

NSDictionary *adic = @{@"aa":@"vb", @"ab": @"va"};
NSDictionary *bdic = @{@"ba": @"va", @"bb":@"vb"};;

RACSequence *aseq = adic.rac_keySequence;
RACSequence *bseq = bdic.rac_keySequence;

RACSequence *cartesian = [[aseq scanWithStart:nil combine:^id(id running, id next_a) {
    return [bseq scanWithStart:nil combine:^id(id running, id next_b) {
        return RACTuplePack(next_a, next_b);
    }];
}] flatten];

RACSequence *filteredCartesian = [cartesian filter:^BOOL(RACTuple *value) {
    RACTupleUnpack(NSString *key_a, NSString *key_b) = value;
    // business logic with keys
    return false;
}];

RACSequence *firstMatch = [filteredCartesian take:1];
于 2013-09-01T20:35:56.043 回答