如何查看对象是否包含在嵌入的NSArray中,然后获取集合中的其他项目

时间:2013-08-23 15:51:24

标签: ios objective-c nsarray

我目前有一个NSArray,其中包含许多NSArray,每个NSArray包含一对NSStrings,如下所示:[["A", "B"], ["U", "A"], ["X", "Y"], ...],我有兴趣首先检查它是否包含特定对象,然后抓住< em>其他配对对象并将其放入数组中。例如,如果我在上面的数组中检查"A",结果数组将包含["B", "U"]

我知道如何迭代每个数组,但是很难决定如何获取数组中的配对对象...谢谢!

for (NSArray *innerArray in outerArray){
    if ([innerArray containsObject: @"A"]){
       //how to extract the other object and save it to an array?
    }
}

3 个答案:

答案 0 :(得分:3)

NSMutableArray *results = [NSMutableArray array];
for (NSArray *innerArray in outerArray){
    // Get the index of the object we're looking for
    NSUInteger index = [innerArray indexOfObject:@"A"];
    if (index != NSNotFound) {
        // Get the other index
        NSUInteger otherIndex = index == 0 ? 1 : 0;

        // Get the other object and add it to the array
        NSString *otherString = [innerArray objectAtIndex:otherIndex];
        [results addObject:otherString];
    }
}

应该做的伎俩。

答案 1 :(得分:2)

如果您确定您的数据将具有您描述的结构,则可以使用内部数组恰好具有2个元素的事实 - 因此“other”元素的索引将为1-indexOfYourElement:

for (NSArray *innerArray in outerArray){
    NSUInteger ix = [innerArray indexOfObject:@"A"];
    if (ix!=NSNotFound){
       id objectToAdd = innerArray[1-ix];
       // Do something with it
    }
}

答案 2 :(得分:0)

这是一种可能的方式:

NSMutableArray* results = [[NSMutableArray alloc] init];
for (NSArray *innerArray in outerArray){
    if ([innerArray containsObject: @"A"]){
        [results addObjectsFromArray: [innerArray enumerateObjectsUsingBlock:^(NSString* obj, NSUInteger idx, BOOL *stop) {
            if (![obj isEqual: @"A"])
            {
                [results addObject: obj];
            }
        }]];
    }
}