문제

To compare the two array I used NSMutableSet and then intersect the two sets to get the common result in an 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. intersectArray is empty . How to get nil value for intersectArray.

도움이 되었습니까?

해결책

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

다른 팁

2 ways to overcome this problem.

1) If no common number then set1 is empty. Thus, before allocating NSArray check if set1 has atleast one element.

[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.

[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])];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top