2

I'm new ios developer, I want to compare and change attributes

Array1 = (object1,object2, object3, object4) Array2 = (object2,object4, object5, object8)

Compare Array1 and Array2 If same objects are in Array2, change attributes in the objects.

In this case above, Object2 and Object4 should be changed..

How should I do??

Please help me!!

user1481757
  • 27
  • 1
  • 5

3 Answers3

3

You can use sets for this

NSMutableSet *array1Set = [NSMutableSet setWithArray:array1];
NSSet *array2Set = [NSSet setWithArray:array2];
[array1Set intersectSet:array2Set];

You now have a set with just the objects which are in both arrays. Now you can use enumerateObjectsUsingBlock: on the set to manipulate the objects or convert the set back to an array NSArray *filteredArray = [array1Set allObjects]

Pfitz
  • 7,336
  • 4
  • 38
  • 51
  • Nice solution. Would be mildly interesting to see how all the possible methods stack up, performance-wise. – jrturton Jul 01 '12 at 08:54
  • have a look eg. here: [when is it better to use a NSSet rather than a NSArray](http://stackoverflow.com/questions/10997404/when-is-it-better-to-use-a-nsset-rather-than-a-nsarray) – Pfitz Jul 01 '12 at 09:00
1

You can use fast enumeration to pass through array 2, then use containsObject: to check if it belongs to array1:

for (id object in array2)
{
    if ([array1 containsObject:object])
    {
        // change your settings here
    }

You could also create a new array using filteredArrayUsingPredicate:, or get the index paths of the matching objects using indexesOfObjectsPassingTest:. You haven't said how many objects are likely to be in your array so I don't know if performance is going to be an issue.

jrturton
  • 118,105
  • 32
  • 252
  • 268
0

I think you'll have to do a n*n search in this case. Loop through every object in Array1, have a nested loop and compare every item in Array2 to the current object (in Array1). If they are equal then change your attribute.

for (int i = 0; i < [array1 count]; i++)
    for (int j = 0; j < [array2 count]; j++)
        if ([array1 objectAtIndex:i] == [array2 objectAtIndex:j]) {
            // do yo thangs
        }
Steven Luu
  • 1,047
  • 1
  • 7
  • 13