gpt4 book ai didi

objective-c - 在 NSArray 中搜索对象属性的快速方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:16:16 25 4
gpt4 key购买 nike

我有一个自定义对象的 NSArray,它们都具有 NSString 类型的@property name。如何快速枚举数组并创建一个新数组,其中仅包含在其 name 属性中具有特定单词的对象?

例如:

CustomObject *firstObject = [[CustomObject alloc] init];
firstObject.name = @"dog";

CustomObject *secondObject = [[CustomObject alloc] init];
secondObject.name = @"cat";

CustomObject *thirdObject = [[CustomObject alloc] init];
thirdObject.name = @"dogs are fun";

NSMutableArray *testArray = [NSMutableArray arrayWithObjects:firstObject,
secondObject,
thirdObject,
nil];

// I want to create a new array that contains all objects that have the word
// "dog" in their name property.

我知道我可以像这样使用 for 循环:

NSMutableArray *newArray = [NSMutableArray array];
for (CustomObject *obj in testArray)
{
if ([obj.name rangeOfString:@"dog"].location == NSNotFound) {
//string wasn't found
}

else {
[newArray addObject:obj];
}
}

但是有没有更有效的方法呢?谢谢!

最佳答案

NSString *searchString = @"dog";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains %@", searchString];
NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];

关于objective-c - 在 NSArray 中搜索对象属性的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12099867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com