NSArray - 检查对象是否在数组中? [英] NSArray - check if objects are in an array?

查看:93
本文介绍了NSArray - 检查对象是否在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个数组。一个是600个对象的大型静态组,另一个是10个对象的小变量组。



我想在两个组之间取任何常见对象并放置它们在一个新数组中。



因此,假设大组包含600个名为1到600的对象。较小的组包含9个对象:1,2,3,4,5 ,6,a,b,c。我希望能够创建一个包含对象1,2,3,4,5,6的新数组。



这样做的最佳方法是什么?

解决方案

您确定需要 NSArray s?对于交叉点,最好使用 NSSet s。有关NSArrays和NSSet的使用的更多信息,请参阅 Cocoa with爱:NSArray或NSSet,NSDictionary或NSMapTable



如果你使用 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,无;

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

您可以从<创建 NSMutableSet code> NSArray 使用 addObjectsFromArray:方法:

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

您可以过滤 NSArray 使用 filterUsingPredicate:方法,但是我从未使用过 NSPredicate ,因此这只是一个假设。 / p>

I have 2 arrays. One is a large static group of 600 objects, the other is a small varying group of 10 objects.

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. I want to be able to create a new array that contains the objects 1, 2, 3, 4, 5, 6.

What is the best way to do this?

解决方案

Are you sure that you need NSArrays? For intersections it would be better to use NSSets. For more information about the usage of NSArrays and NSSet please refer to Cocoa with Love: NSArray or NSSet, NSDictionary or 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:

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:

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 NSPredicates therefore this is only an assumption.

这篇关于NSArray - 检查对象是否在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆