简体   繁体   中英

Checking an array if it contains an object by a specific property, objective-c

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

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.

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
        }
    }
}

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

And likewise for Bar.

Use NSMutableSet's intersectSet: method.

  1. Pull out the array of property values you want to intersect, and convert your first array to a mutable set: NSMutableSet *setA = [NSMutableSet setWithArray:[arrayA valueForKey:@"name"]];

  2. Intersect it with the property values in array B. [setA intersectSet:[NSSet setWithArray:[arrayB valueForKey:@"name"]];

If you wanted to combine it into one really long line, you'd do this:

NSSet *commonProperties = [[NSMutableSet setWithArray:[arrayA valueForKey:@"name"]] intersectSet:[NSSet setWithArray:[arrayB valueForKey:@"name"]]];

Of course, this is only going to give you the name property, not the object itself. If you wanted the entire object, override isEqual: and do the name check in there. Then you can eliminate the valueForKey: part and just intersect the two sets.

The remaining values will be the common values. NSSet string comparison uses isEqualToString: behind the scenes for NSString objects.

Even if you use predicate, internally it will take each object in array and compare. Array is a collection not like primitive data types and there is no way to compare in a single fly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM