简体   繁体   English

NSArray - 检查对象是否在数组中?

[英]NSArray - check if objects are in an array?

I have 2 arrays. 我有2个阵列。 One is a large static group of 600 objects, the other is a small varying group of 10 objects. 一个是600个对象的大型静态组,另一个是10个对象的小组。

I want to take any common objects between the two groups and put them in a new array. 我想在两个组之间采用任何常见对象并将它们放在一个新数组中。

So lets say the large group contains 600 objects named 1 to 600. The smaller group contains 9 objects: 1, 2, 3, 4, 5, 6, a, b, c. 因此,假设大组包含600个名为1到600的对象。较小的组包含9个对象:1,2,3,4,5,6,a,b,c。 I want to be able to create a new array that contains the objects 1, 2, 3, 4, 5, 6. 我希望能够创建一个包含对象1,2,3,4,5,6的新数组。

What is the best way to do this? 做这个的最好方式是什么?

Are you sure that you need NSArray s? 你确定你需要NSArray吗? For intersections it would be better to use NSSet s. 对于交叉点,最好使用NSSet For more information about the usage of NSArrays and NSSet please refer to Cocoa with Love: NSArray or NSSet, NSDictionary or NSMapTable . 有关NSArrays和NSSet的使用的更多信息,请参阅Cocoa with Love:NSArray或NSSet,NSDictionary或NSMapTable

If you are using NSSet you have to create a new NSMutableSet , which has the method intersectSet: , which can be used for your purpose: 如果您正在使用NSSet ,则必须创建一个新的NSMutableSet ,它具有intersectSet:方法,可用于您的目的:

NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil];
NSMutableSet *set2 = [[NSMutableSet alloc] initWithObjects:@"2", @"4", @"6", @"8", @"10", @"12", @"14", @"18", nil];

NSLog(@"set1: %@", set1);
NSLog(@"set2: %@", set2);
[set1 intersectSet:set2];
NSLog(@"isec: %@", set1);

You can create a NSMutableSet from an NSArray using the addObjectsFromArray: method: 您可以使用addObjectsFromArray:方法从NSArray创建NSMutableSet

NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObjectsFromArray:array];

It may be that you can also filter the NSArray using the filterUsingPredicate: method, however I have never worked with NSPredicate s therefore this is only an assumption. 可能你也可以使用filterUsingPredicate:方法过滤NSArray ,但是我从未使用过NSPredicate因此这只是一个假设。

The easiest (but not necessarily fastest (?)) way would be something like 最简单的(但不一定是最快的(?))方式就是这样的

NSMutableSet *intersection = [NSMutableSet setWithArray:smallArray];
[intersection intersectSet:[NSSet setWithArray:bigArray];
NSArray *result = [NSArray arrayWithSet:intersection];

You'll have to sort the resulting array again, however. 但是,您必须再次对生成的数组进行排序。

You could use NSPredicate. 你可以使用NSPredicate。 I hope that this post could be usefull to start... 我希望这篇文章可以帮助你开始......

http://marcocattai.posterous.com/nsarray-nspredicate-filter http://marcocattai.posterous.com/nsarray-nspredicate-filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM