微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在NSArray中搜索对象属性的快速方法

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

解决方法

我有一个NSArray自定义对象,它们都具有@property
name类型NSString。如何快速枚举数组并创建一个仅包含其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];
    }
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。