在 Objective-C 中将 NSArray 过滤为新的 NSArray [英] filtering NSArray into a new NSArray in Objective-C

查看:20
本文介绍了在 Objective-C 中将 NSArray 过滤为新的 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.

有更好的方法吗?

推荐答案

NSArrayNSMutableArray 提供了过滤数组内容的方法.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 filteredArrayUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }

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

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