Filter array using custom object property [closed]

☆樱花仙子☆ 提交于 2019-12-11 10:44:19

问题


I have an array of objects.Each object has its own properties (name, desc, status). name and desc are NSString and status is BOOL.

I want to filter this array by status property. Ex: Get all objects with status == YES.

How can I achieve this?


回答1:


Try use NSPredictate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status = %@", @"YES"];
NSArray *filterArray = [array filteredArrayUsingPredicate:predicate];

This gives you an array with all object where status is equal YES.




回答2:


Try this,

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"status = YES"];
NSArray *filteredArray = [yourArray filteredArrayUsingPredicate:predicate];



回答3:


Hi you can try this one,

NSMutableArray *array =[NSMutableArray arrayWithObjects:@"Apple", @"Animal", @"baby", @"ball", nil];

NSPredicate *aPredicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[a] 'b'"];
NSArray *beginWithA =
    [array filteredArrayUsingPredicate:aPredicate];

The beginWithA array will have { @"Apple", @"Animal" }.

NSPredicate *bPredicate =
    [NSPredicate predicateWithFormat:@"SELF contains[b] 's'"];
[array filterUsingPredicate:bPredicate];
The array will have { @"baby", @"ball" }

Thanks



来源:https://stackoverflow.com/questions/21572509/filter-array-using-custom-object-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!