iosnsmutablearrayfast-enumeration

How to check to see if an object exists in NSMutableArray without knowing the index, and replace it if it exists, in iOS?


I have an NSMutableArray that contains objects of type Person. The Person object contains parameters of NSString *name, NSString *dateStamp, and NSString *testScore. What I would like to do using fast enumeration, is to check to see in the NSMutableArray *testResults, is see if an object with the same name parameter exists.

If it does, then I want to replace the existing object in the NSMutableArray, with the object that I am about to insert which will have the most current dateStamp, and testScore values. If an object with no matching name parameter is found, then simply insert the object that I have.

My code so far looks like this:

This is the code that creates my object that I am about to insert:

Person *newPerson = [[Person alloc] init];
    [newPerson setPersonName:newName]; //variables newName, pass, and newDate have already been 
    [newPerson setScore:pass];      //created and initialized
    [newPerson setDateStamp:newDate];

and here is the code where I try to iterate through the NSMutableArray to see if an object with the same name parameter already exists:

for (Person *checkPerson in personList) { //personList is of type NSMutableArray

        if (newPerson.newName == checkPerson.name) {

           //here is where I need to insert the code that replaces checkPerson with newPerson after a match has been found   


        }

        else {

             personList.addObject(newPerson); //this is the code that adds the new object to the NSMutableArray when no match was found.
    }

}

It's not a very complicated problem, but I am confused as to how to go about finding a match, and then replacing the actual object without knowing ahead of time what index the object resides in.


Solution

  • You want to use indexOfObjectPassingTest to look for a match:

        NSInteger indx = [personList indexOfObjectPassingTest:^BOOL(Person *obj, NSUInteger idx, BOOL *stop) {
            return [obj.name isEqualToString:newPerson.name];
        }];
        if (indx != NSNotFound) {
            [personList replaceObjectAtIndex:indx withObject:newPerson];
        }else{
            [personList addObject:newPerson];
        }
    

    Notice that I used isEqualToString: to compare the two strings not ==. That mistake has been asked about and answered a million times on this forum.

    You have some inconsistency in your naming. In the question, you say the Person objects have a name property, but when you create a new person you use setPersonName, which would imply that the property name is personName. I assumed, just name in my answer.