在一个NSArray搜索对象的属性快速的方式 [英] Fast way to search the properties of objects in an NSArray

查看:442
本文介绍了在一个NSArray搜索对象的属性快速的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的NSArray 所有具有类型的@property 名称自定义对象的的NSString 。我怎样才能通过阵列快速枚举,并创建一个新数组,它仅包含有一个特定的词在他们的名称属性?

对象

例如:

  CustomObject * firstObject = [[CustomObject页头]初始化];
firstObject.name = @狗;

CustomObject * secondObject = [[CustomObject页头]初始化];
secondObject.name = @猫;

CustomObject * thirdObject = [[CustomObject页头]初始化];
thirdObject.name = @狗是乐趣;

NSMutableArray里* testArray = [NSMutableArray的arrayWithObjects:firstObject,
                                                             secondObject,
                                                             thirdObject,
                                                             零];

//我要创建一个新的数组,其中包含有单词的所有对象
以他们的名义财产//狗。
 

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

 的NSMutableArray * newArray = [NSMutableArray的阵列]
为(在testArray CustomObject * OBJ)
{
    如果([obj.name rangeOfString:@狗。位置== NSNotFound){
        //未找到字符串
    }

    其他 {
        [newArray ADDOBJECT:OBJ]。
    }
}
 

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

解决方案

 的NSString * searchString = @狗;
NS predicate * predicate = NS predicate predicateWithFormat:@SELF.name包含%@,searchString]。
NSArray的* filteredArray = [testArray filteredArrayUsing predicate:predicate]。
 

I have an NSArray of custom objects that all have a @property name of type NSString. How can I quickly enumerate through the array and create a new array that contains only the objects that have a specific word in their name property?

For instance:

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. 

I know I could use a for loop like so:

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

    else {
        [newArray addObject:obj];
    }
}

But is there a more efficient way? Thanks!

解决方案

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

这篇关于在一个NSArray搜索对象的属性快速的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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