How to compare arrays? And change attributes?

梦想的初衷 提交于 2019-12-02 01:28:46

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]

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.

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
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!