Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge NSMutableArray with a NSArray, filtering the duplicates

Tags:

objective-c

I have two arrays, an NSMutableArray and an NSArray. The NSMutableArray is the "store", it stores results from a source of NSArrays. Every 5 minute, a new NSArray comes in and the data needs to be filtered and sorted.

Sorting by date is pretty easy, so I managed to get the NSArray sorted by NSDate. Sorting the other array is not necessary, as it would only cause confusion with the user.

What I want to do: the NSArray has a lot of different objects that all respond to -[object name], returning an NSString. The NSArray needs to be merged into the NSMutableArray, only adding new objects.

The merging itself is no problem, but performance is. The NSMutableArray can contain up to 3000 items, and the NSArray can contain up to 250 items, although usually only 5 or 6 of these have to be merged into the NSMutableArray.

So, my question is: how do you merge two arrays in Objective-C, filtering the duplicates, without iterating (250*3000) times?

Tom

Edited to clarify something
The "duplicate" objects are objects that are duplicate to the user but not to the code. They have the same name, but not the same address.

More clarification: @"value" != @"value" // true

like image 377
Tom van der Woerdt Avatar asked Dec 15 '10 21:12

Tom van der Woerdt


2 Answers

Is name a property of the objects being stored in the arrays? If so, you could use a fairly simple NSPredicate to filter the immutable array before adding the results to the mutable one. Here's an example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NONE name == %@.name", mutableArray];
resultsArray = [immutableArray filteredArrayUsingPredicate:predicate];
[mutableArray addObjectsFromArray:immutableArray];
like image 53
Endemic Avatar answered Oct 21 '22 02:10

Endemic


How about this:

[mutable removeObjectsInArray:newArray];
[mutable addObjectsFromArray:newArray];

It isn't the fattest, but is easy to implement :)

like image 38
Rodrigo Avatar answered Oct 21 '22 00:10

Rodrigo