优雅的方式来获得一个Objective-C数组特定类型的所有对象 [英] Elegant way to get all objects of a specific type in an Objective-C array

查看:149
本文介绍了优雅的方式来获得一个Objective-C数组特定类型的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以做

for (id obj in array)
{
    if ([obj isKindOfClass:[Elephant class]])
        [elephants addObject:obj];
}

但我觉得必须有这样做的更优雅的方式。我看着滤波阵列,但不能拿出一个好的predicate。思考?

but I feel there must be a more elegant way of doing this. I've looked at filtering arrays but can't come up with a good predicate. Thoughts?

推荐答案

在predicate会是这样

The predicate would be something like

Class ec = [Elephant class];
NSPredicate *elePred = [NSPredicate predicateWithFormat:@"class==%@", ec];
NSArray *elephants = [array filteredArrayUsingPredicate:elePred];

NSPredicate *elePred = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", ec];

我发现predicates相当,呃..应该说重。我可能会preFER您code这一点。

I have found predicates to be quite, er.. shall we say "Heavy". I would probably prefer your code to this.

如果你只是寻找来调剂你的生活一点,你就可以使用块加少许并发...

If you are just looking to spice up your life a little you could use blocks to add a little concurrency…

    NSMutableArray *results = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
        if([obj isKindOfClass:[Elephant class]])
            [results addObject:obj];
    }];

这篇关于优雅的方式来获得一个Objective-C数组特定类型的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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