检查数组是否包含特定属性objective-c的对象 [英] Checking an array if it contains an object by a specific property, objective-c

查看:32
本文介绍了检查数组是否包含特定属性objective-c的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个自定义对象数组.两者都具有NSString * name的属性.我想检查

I have two arrays of custom objects. Both have properties of NSString *name. I want to check if

object.name in array1 == object.name in array2

我该怎么做?我是否必须构成谓词?我知道我可以强行使用它,只是枚举array2中的对象以检查它是否具有相同的名称,但是我不知道是否存在执行此任务的性能更好或理想的方法.谢谢.

How would I do that? Do I have to form a predicate? I know I can brute force it and just enumerate over the objects in array2 to check if it has the same name, but I didn't know if there was a better-performing or ideal way to do this task. Thanks.

推荐答案

您的想法很好.如果您确实了解类型,请指定它们,以使编译器和以后阅读代码的人员可以清楚地看到它们.另外,使用isEqualToString:比较字符串.

What you're thinking is fine. To the extent you do know types, specify them to be clear with the compiler and people reading the code in the future. Also, use isEqualToString: to compare strings.

for (Foo *foo in myFooCollection) {
    for (Bar *bar in myBarCollection) {
        if ([foo.name isEqualToString:bar.name]) {
            // match
        }
    }
}

您可能要考虑的另一件事是在Foo和Bar对象上实现compare.

Another thing you might consider is implementing compare: on both Foo and Bar objects.

// Foo.m
- (NSComparisonResult)compare:(id)otherObject {
    if ([otherObject isKindOfClass:[Bar self]]) {
        Bar *itsABar = (Bar *)otherObject;
        return [self.name compare:itsABar.name];
    } 
    return [super compare:otherObject];
}

酒吧也是如此.

这篇关于检查数组是否包含特定属性objective-c的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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