将NSArray过滤到objective-c中的新NSArray中 [英] filtering NSArray into a new NSArray in objective-c

查看:132
本文介绍了将NSArray过滤到objective-c中的新NSArray中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSArray ,我想用原始数组中的对象创建一个新的 NSArray 符合一定标准。该标准由返回 BOOL 的函数决定。

I have an NSArray and I'd like to create a new NSArray with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a BOOL.

我可以创建一个 NSMutableArray ,遍历源数组并复制过滤器函数接受的对象,然后创建一个不可变的版本。

I can create an NSMutableArray, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.

有更好的方法吗?

推荐答案

NSArray NSMutableArray 提供了过滤数组内容的方法。 NSArray 提供 filteredArrayUsingPredicate:,它返回包含接收器中与指定谓词匹配的对象的新数组。 NSMutableArray 添加 filterUsingPredicate:,它根据指定的谓词评估接收者的内容,只留下匹配的对象。这些方法如下例所示。

NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray adds filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.

NSMutableArray *array =
    [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];

NSPredicate *bPredicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *beginWithB =
    [array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Bill", @"Ben" }.

NSPredicate *sPredicate =
    [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];
[array filterUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }

这篇关于将NSArray过滤到objective-c中的新NSArray中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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