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