0

Is it possible to subtract the values in one NSMutableArray from those in another NSMutableArray, while preserving any remaining like values (keep duplicate copies)? I don't want to remove every instance of the value, just a 1 for 1 subtraction.

I'm working with CGPoints.

Array1 ccp(1,1) ccp(1,1) ccp(1,2) ccp(1,3)

Array2 ccp(1,1)

Desired output: Array3 ccp(1,1) ccp(1,2) ccp(1,3)

1 Answer 1

1

Sorry I didn't understand your question properly before. Maybe you could try something like:

NSMutableArray *points1 = [NSMutableArray arrayWithObjects:
                            [NSValue valueWithCGPoint:CGPointMake(1, 1)],
                            [NSValue valueWithCGPoint:CGPointMake(1, 1)],
                            [NSValue valueWithCGPoint:CGPointMake(1, 2)],
                            [NSValue valueWithCGPoint:CGPointMake(1, 3)], nil];

NSArray        *points2 = [NSArray arrayWithObject:
                            [NSValue valueWithCGPoint:CGPointMake(1, 1)]];

NSInteger index = NSNotFound;

for (NSValue *point in points2) {
    index = [points1 indexOfObject:point];

    if (NSNotFound != index) {
        [points1 removeObjectAtIndex:index];
    }
}

NSLog(@"%@", points1);

=> 2012-03-04 00:02:26.376 foobar[19053:f803] (
       "NSPoint: {1, 1}",
       "NSPoint: {1, 2}",
       "NSPoint: {1, 3}"
   )

Update

NSNotFound is defined in NSObjCRuntime.h. You can find this out by command + clicking on the symbol NSNotFound in Xcode.

The definition is

 enum {NSNotFound = NSIntegerMax};

The reason I knew to use this is by looking at the NSArray documentation for the indexOfObject: method, which reads:

Return Value
The lowest index whose corresponding array value is equal to anObject. If none of the objects in the array is equal to anObject, returns NSNotFound.

Sign up to request clarification or add additional context in comments.

3 Comments

This works great, thanks! Could you comment on what exactly NSNotFound is doing? After reading up on it I think I understand what's going on, but it's not 100% clear for me. Thanks again.
@Vanny I've added some clarification
Thank for the very thorough answer, much appreciated. I wish I could upvote this answer, but I'm new.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.