比较数组ios

如何比较2个不同值的数组数组有一个词,另一个有图像

NSDictionary *dict = [NSDictionary dictionaryWithObjects:array2 forKeys:array1]; 

我认为你需要使用一个NSDictionary 。 这是你如何做的(使用新的Objective C文字语法)

 NSDictionary *dictionary = @{ @"dog" : @"dog.jpg", @"apple" : @"apple.jpeg", @"clown" : @"clown.gif" }; 

从这个字典检索“狗”的图像文件名做到这一点:

 NSString *fileName = dictionary[@"dog"]; 

当一个button被点击时,您可以简单地获取该值并search到图像数组以获得匹配的图像名称,例如,

 NSString *selValue = @"dog"; for (NSString *obj in imagesArray) { if ([obj rangeOfString:selValue].location != NSNotFound) { NSString *imageName = obj; break; } } 

这不是完全符合您的要求的代码, 可以作为一个想法,因为你有图像。

假设你的单词和图像在相同的索引

我刚刚实现了类似于名为A.jpg的string的情况,这个想法保持不变,需要进行相应的转换。

 NSMutableArray *words=[[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"D", nil]; NSMutableArray *images=[[NSMutableArray alloc]initWithObjects:@"A.jpg",@"B.jpg",@"C.jpg",@"D.jpg", nil]; id selectedWord=@"C";//This is storing which word you have selected id selectedImage=[images objectAtIndex:[words indexOfObject:selectedWord]];//this will store the image NSLog(@"%@",selectedImage);//now you can display the image in imageview 

如果单词和图片不是任何顺序的话

 //words array is of no use, you can simply find which word you selected by extracting before "." , but as I am not aware of exact requirement I have left words array. NSMutableArray *words=[[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"D", nil]; NSMutableArray *images=[[NSMutableArray alloc]initWithObjects:@"B.jpg",@"D.jpg",@"C.jpg",@"A.jpg", nil]; id selectedWord=@"B"; NSInteger indexOfSelectedWord; for (NSString *imageName in images) { if ([[[imageName componentsSeparatedByString:@"."]objectAtIndex:0]isEqualToString:selectedWord]) { indexOfSelectedWord=[images indexOfObject:imageName]; } } id selectedImage=[images objectAtIndex:indexOfSelectedWord]; NSLog(@"%@ & %@",selectedWord ,selectedImage);