0

嗨,我想知道如何将 setObjects 的内容与 NSDictionary 中的键进行比较:这是我正在使用的代码:

[INNumbers setObject:@"0,1,2,3,4,5,6,7" forKey:@"0"];
[INNumbers setObject:@"4,5,6,7,8,9,10,11" forKey:@"1"];

我想知道如何比较这两个键并找出是否有类似的数字,例如两者中是否出现 7?

//this will get the numbers in the keys for me
     id number1 = [INNumbers objectForKey:@"0"];
     id number2 = [INNumbers objectForKey:@"1"];

但我不确定如何比较 number1 和 number2 检索到的内容。

4

2 回答 2

1

在您的示例中,存储在字典中的值是字符串文字,很难重复解析和测试成员资格测试。也许您想使用NSSets:

#import <Foundation/Foundation.h>

int main()
{
    NSSet *numbers1 = [NSSet setWithObjects:@0, @1, @2, nil];
    NSSet *numbers2 = [NSSet setWithObjects:@0, @4, @5, nil];

    if([numbers1 intersectsSet : numbers2]) {
        NSLog(@"The two sets have at least one element in common!");

        /* Let's obtain the intersection: */
        NSSet *common = [numbers1 objectsPassingTest:^BOOL(id obj, BOOL *stop) {
                        if ([numbers2 containsObject:obj]) {
                            return YES;
                        } else {
                            return NO;
                        }
        }];
        for (id o in common) {
            NSLog(@"%@", o);
        }
    }
    return 0;
}
于 2013-09-05T13:01:14.190 回答
1

如果我不是被迫使用字符串,我会这样做:

NSArray *nums0 = @[@1,@2,@3];
NSArray *nums1 = @[@3,@4,@5];

NSMutableSet *intersection = [NSMutableSet setWithArray:nums0];
[intersection intersectSet:[NSSet setWithArray:nums1]];

NSArray *numsInCommon = [intersection allObjects];

numsInCommon 将包含@3,这是两个数组中的数字

于 2013-09-05T13:03:03.353 回答