Pregunta

I have two NSMutableDictionay, let's call the one expected "A" and the one as the result of my operation "B"

I want to insert to a "C" NSMutableDictionary the differences between "A" and "B".

I use the if (![dicExpected isEqualToDictionary:actualDic]) {

But what's the best way to get the non common pairs ?

¿Fue útil?

Solución

The question contains a few ambiguities. I think the intent is probably to assume the two dictionaries have matching keys and output the "b" dictionary values as the difference. The code below does that, but considers the alternative interpretations:

// use the keys in dA to find non-matching values in dB

- (NSDictionary *)nonMatching:(NSDictionary *)dA comparedTo:(NSDictionary *)db {

    NSMutableDictionary *diff = [NSMutableDictionary dictionary];

    for (id key in [dA allKeys]) {
        id valueA = dA[key];
        id valueB = dB[key];
        if (valueB && ![valueA isEqual:valueB]) {

            // here, the question is ambiguous. what should go in the output
            // for non-matching values? the b value? both?
            // both would look like this:  diff[key] = @[valueA, valueB];
            // but lets guess that you want just the b value

            diff[key] = valueB;
        }
        // another ambiguity in the question is what to do with keys in the dA that
        // don't appear in dB.  One idea is to ignore them, which is what happens here
        // without more code.  that's probably what you need.  anther idea would
        // be to record a null in the output for those, like this:
        // if (!valueB) diff[key] = [NSNull null];
    }

    // the last ambiguity is dealing with dB keys that don't appear in dA
    // again, do nothing is probably the idea you're looking for, but this would work, too:

    // for (id keyB in [dB allKeys]) {
    //     if (!dA[keyB]) diff[keyB] = dB[keyB];
    // }

    return diff;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top