在一个NSArray搜索对象的属性快速的方式属性、对象、快速、方式

2023-09-11 02:39:17 作者:真爱像UFO听说过没见过

我有一个的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]。
 
5 coreData基本扩展 保存NSArray

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];

 
精彩推荐
图片推荐