繁体   English   中英

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

[英]Compare two array and get the common value back in an array

为了比较我使用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值。

有两种方法可以解决这个问题。

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])];
}

尝试使用:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM