简体   繁体   English

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

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

To compare the two array I used NSMutableSet and then intersect the two sets to get the common result in an array. 为了比较我使用NSMutableSet的两个数组,然后将两个集相交以获得数组中的公共结果。 NSMutableSet *set1 = [NSMutableSet setWithArray:array]; 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])];

It gives me perfect answer but it get crashed when set1 does not have common element as that of set2. 它给了我完美的答案但是当set1没有set2的公共元素时它会崩溃。 intersectArray is empty . intersectArray是空的。 How to get nil value for intersectArray. 如何获得intersectArray的nil值。

2 ways to overcome this problem. 有两种方法可以解决这个问题。

1) If no common number then set1 is empty. 1)如果没有公共号,则set1为空。 Thus, before allocating NSArray check if set1 has atleast one element. 因此,在分配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) When you want to get an element of an array then before getting element check if array is not empty and it has an element at index you want to get. 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])];
}

try to use: 尝试使用:

 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