比较两个数组并在数组中返回公共值

时间:2013-06-19 15:19:10

标签: iphone ios nsset nsmutableset

为了比较我使用NSMutableSet的两个数组,然后将两个数组相交以获得数组中的常见结果。 NSMutableSet * set1 = [NSMutableSet setWithArray:array];

[set1 intersectSet:[NSSet setWithObject:[NSNumber numberWithInt:70]]];

NSArray *intersectArray = [[NSArray alloc]init];
intersectArray =[set1 allObjects];
NSLog(@"the testing array is %@",[intersectArray objectAtIndex:0])];

它给了我完美的答案但是当set1没有set2的公共元素时它会崩溃。 intersectArray是空的。如何获得intersectArray的nil值。

2 个答案:

答案 0 :(得分:1)

克服这个问题的两种方法。

1)如果没有公共号码,则set1为空。因此,在分配NSArray之前,检查set1是否至少包含一个元素。

[set1 intersectSet:[NSSet setWithObject:[NSNumber numberWithInt:70]]];

if([set1 count]) {
    NSArray *intersectArray = [[NSArray alloc]init];
    intersectArray = [set1 allObjects];
    NSLog(@"the testing array is %@",[intersectArray objectAtIndex:0])];
}

2)当你想获得一个数组的元素时,那么在获取元素之前,如果数组不是空的并且它有一个你希望得到的索引元素。

[set1 intersectSet:[NSSet setWithObject:[NSNumber numberWithInt:70]]];
NSArray *intersectArray = [[NSArray alloc]init];
intersectArray = [set1 allObjects];

if(intersectArray.count && intersectArray.count > indexOfElement) {
    NSLog(@"the testing array is %@",[intersectArray objectAtIndex:0])];
}

答案 1 :(得分:1)

尝试使用:

 if ([set1 intersectSet:[NSSet setWithObject:[NSNumber numberWithInt:70]]])

{
NSArray *intersectArray = [[NSArray alloc]init];
intersectArray =[set1 allObjects];
NSLog(@"the testing array is %@",[intersectArray objectAtIndex:0])];
{