0

为了比较这两个数组,我使用了 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 值。

4

2 回答 2

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])];
{
于 2013-06-20T13:00:44.293 回答
1

2种方法来克服这个问题。

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])];
}
于 2013-06-19T15:52:24.153 回答