2016-09-28 39 views
1

嗨,我有兩個nsarrays。如何比較兩個不同值的nsarrays?

數組A:

arrProductSelection = [[NSArray alloc]initWithObjects:@"English",@"German",@"Russian",@"Chinese",@"Spanish",@"French",@"French",@"French",@"French",@"French",@"French",@"French",@"French",nil]; 

陣列B:

arrProductSelectionB = [[NSArray alloc]initWithObjects:@"deselcted",@"selected",@"selected",@"selected",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",nil]; 

我需要比較兩個數組,並通過與作爲選擇具有值B陣列進行比較得到從陣列A的值。那就是我應該用德文,中文和俄文用逗號分隔nsstring。

+0

這兩個數組的數量是否相同? –

+0

您應該爲此使用字典。 – Janmenjaya

+0

是的,他們是相同的 –

回答

3

試試這個:

NSMutableArray *arrSelected = [[NSMutableArray alloc] init]; 

NSArray *arrProductSelection = [[NSArray alloc]initWithObjects:@"English",@"German",@"Russian",@"Chinese",@"Spanish",@"French",@"French",@"French",@"French",@"French",@"French",@"French",@"French",nil]; 

NSArray *arrProductSelectionB = [[NSArray alloc]initWithObjects:@"deselcted",@"selected",@"selected",@"selected",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",@"deselcted",nil]; 

for(int i = 0; i< arrProductSelectionB.count-1;i ++) { 
    if ([arrProductSelectionB[i] isEqualToString:@"selected"]) { 
     [arrSelected addObject:arrProductSelection[i]]; 
    } 
} 

NSString *strSelected = [arrSelected componentsJoinedByString:@","]; 

NSLog(@"%@", strSelected);//output: German,Russian,Chinese 
+0

很快就會有綠色的勾號 –

0

首先我會確保兩個數組對安全的東西一樣一樣的計數器

if (arrProductSelection.count == arrProductSelectionB) { 

//than all you need is one for cycle something like : 

    for (int i = 0; i < arrProductionSelectionB.count; i++) { 
     if ([arrProductionSelectionB[i] isEqualToString: @"selected"]) { 
     do something magically with arrProductSelection[i]; 
    } 
    } 
} 
0

如果你可以讓這種類型的數組然後管理伊斯利。

(
     { 
     flag = deselcted; 
     name = English; 
    }, 
     { 
     flag = selected; 
     name = German; 
    }, 
     { 
     flag = deselcted; 
     name = Russian; 
    }, 
     { 
     flag = deselcted; 
     name = Chinese; 
    } 
) 

==>數組[(辭典),(詞典),...]

0

如果需要導致陣列,下面是函數:

NSMutableArray*resultArray=[[NSMutableArray alloc]init]; 

    for(int i=0; i<arrProductSelectionB.count;i++){ 
     if ([[arrProductSelectionB objectAtIndex:i]isEqualToString:@"selected"]) { 
      [resultArray addObject:[arrProductSelection objectAtIndex:i]]; 
     } 
    } 

resultArray擁有您需要的值。