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

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

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

How should I do it? Should I form a predicate? I know that I can go too far and simply list the objects in array2 to check if it has the same name, but I did not know if there was a more efficient or ideal way to accomplish this task. Thank.

+3
source share
3 answers

What you think is beautiful. To the extent that you know the types, specify them so that they are 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.

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

.

+2

NSMutableSet intersectSet:.

  • , , : NSMutableSet *setA = [NSMutableSet setWithArray:[arrayA valueForKey:@"name"]];

  • B. [setA intersectSet:[NSSet setWithArray:[arrayB valueForKey:@"name"]];

, :

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

, name, . , isEqual: . valueForKey: .

. NSSet isEqualToString: NSString.

+2

Even if you use a predicate, inside it will take every object in the array and compare. An array is collectionnot like primitive data types, and there is no way to compare in one fly.

+1
source

All Articles