How to get last element from NSMutableArray in which status as complete?

故事扮演 提交于 2019-12-08 07:12:45

问题


I have an array of dictionaries in following format

[
{
 "status":"not completed",
 "rating":2 
},{
"status":"completed",
 "rating":2 
},{
"status":"not completed",
"rating":"<null>" 
},{
 "status":"completed",
 "rating":"<null>"},{
"status":"not completed",
"rating":"<null>" 
}
]

and from this i want response as last object where status is completed and rating is null

output
{
     "status":"completed",
     "rating":"<null>"
}

how do i get second element easily without any big iteration.

in real case this array might contains 150-300 elements.

  -(void)checkRecentUnratedOrder:(NSMutableArray *)order{

    NSLog(@"trip log - %@",[order valueForKey:@"status"]); // total 5 objects inside array in that 4 of them are completed

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.status == completed"];
    NSArray *arr = [order filteredArrayUsingPredicate:predicate];

    NSLog(@"trip arr%@",arr);




}

console


回答1:


You need to predicate your array like this

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.status == 'completed'"];
NSArray *arr = [order filteredArrayUsingPredicate:predicate];
// Now `arr` contains all the `dictionary` that `status` key contain `completed` value. 


来源:https://stackoverflow.com/questions/38408534/how-to-get-last-element-from-nsmutablearray-in-which-status-as-complete

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