1

I have two array, called array1 and array2. I would like to remove every object from array1 that's value of the "nameId" key can be find in both array. Actually I'm trying it in a for loop, but it doesn't make sense. It doesn not crash, it just simply calls the log in the else statement, that I don't understand why happens. Maybe somebody could show me the right solution.

NSMutableArray *newArray = [self.array1 mutableCopy];

for (PFObject * object in newArray) {

    PFObject *placeholderObject = object;

    for (PFObject *object2 in self.array2) {

        if ([placeholderObject[@"nameId"] isEqualToString:object2[@"nameId"]]) {

            [self.array1 removeObject:object];

            NSLog (@"EXISTING OBJECT FOUND %@", object);
        } else {


            NSLog(@"UNIQUE OBJECT FOUND %@", idO[@"hirCime"]);

        }


    }


}
cimp23
  • 49
  • 5
  • 1
    if `array1` and `array2` are immutable arrays, shouldn't you should be doing "`[newArray removeObject:object]`"? Also, did you step through this via the Xcode debugger to see if there is a case where placeHolderObject's "`nameId`" is equal to the what's in object2 ? – Michael Dautermann Sep 22 '15 at 23:12
  • @MichaelDautermann It isn't a good idea to remove items from arrays in the body of fast enumeration loops - it will likely trigger "NSArray was mutated while being enumerated" exceptions. OP should definitely check that `if` statement though. – Rich Tolley Sep 22 '15 at 23:16
  • yeah, you're right about removing items from arrays like that. I usually use [reverse enumeration](http://stackoverflow.com/questions/24508592/how-to-iterate-for-loop-in-reverse-order-in-swift) in cases where I'm removing items from a mutable array. – Michael Dautermann Sep 22 '15 at 23:22
  • possible duplicate of [How to remove objects from array based on other array's object](http://stackoverflow.com/questions/32741424/how-to-remove-objects-from-array-based-on-other-arrays-object) – Fantini Sep 25 '15 at 15:44

1 Answers1

0

When creating a mutableCopy of an array you create a new array with a copy of every object in it but they aren't the same ones, so object is a member of newArray but is not a member of self.array1 so you can't remove it from that array.

This should work:

// Creates a new empty mutable array
NSMutableArray *newArray = [@[] mutableCopy]; 

for (PFObject *object in self.array) {

    BOOL found = NO;

    for (PFObject *object2 in self.array2) {

        if ([object[@"nameId"] isEqualToString:object2[@"nameId"]]) {
            found = YES;
            NSLog (@"EXISTING OBJECT FOUND %@", object);
            break;

        } else {
            NSLog(@"UNIQUE OBJECT FOUND %@", idO[@"hirCime"]);
        }
    }

    if (!found) {
        [newArray addObject:[object copy]];
    }
}

// And maybe you want this 
self.array = newArray;
Fantini
  • 2,067
  • 21
  • 32