开发者

NSMutable Array object compare

I want to compare to mutablearray object condition is below...

array1 = 1,2,3,4; array2 = 2,1,4,3,6,7;

compare this two array object & if the object is already in array then not add otherwise add in array3.

all th开发者_运维百科e array are NSMutable array

please help


The easiest way is using sets

NSMutableSet *set = [NSMutableSet setWithArray:array1];
[set addObjectsFromArray:array2];

NSArray *array = [set allObjects];

array will give the merged third array without duplicates.


for (int i = 0; i < [array1 count]; i++)
{
    BOOL addThisNumber = YES;
    for (int j = 0; j < [array2 count]; j++)
    {
        int first = [array1 objectAtIndex:i];
        int second = [array2 objectAtIndex:j];
        if ([first compare:second] == NSOrderedSame)
        {
            addThisNumber = NO;
        }
    }

    if (addThisNumber)
    {
        [array3 addObject:first];
    }
}

What I usually do is check for each object in the first array whether or not it occurs in the second array. In the end, add the object if it wasn't found before.

EDIT: Jhaliya's method works much faster then my answer, and using sets like 7KV7's answer is the proper way to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜