views:

34

answers:

2

I currently have an NSMutableArray which stores a collection of Video objects.

Each Video object has an ID and TITLE.

I also have another NSMutableArray of video objects generated from parsing an XML API call.

When the user hits a 'synchronize' button, I want the system to be able to figure out the minimum number of operations needed (delete & add videos) to bring both lists in sync.

What is the optimal way of doing this? Does Objective-C define any methods of doing this? If not, is there a special algorithm I can implement?

(Personally, I'd rather not loop through each and every item in both lists)

A: 

Supposing you are only adding and deleting videos you can have two NSMutableDictionaries, one for deleting and the other for adding videos. When you add a video you add an entry to the ADDDictionary, when you delete one you first check if it appears as an entry in the ADDDictionay and if so you delete it, else you add an entry to the DELDictionary.

rano
A: 

You could use -removeObjectsInArray: to get the differences if you implemented isEqual: and hash sensibly:

NSMutableArray *old = ...;
NSMutableArray *new = ...;

NSMutableArray *toAdd    = [new mutableCopy];
NSMutableArray *toDelete = [old mutableCopy];
[toAdd    removeObjectsInArray:old];
[toDelete removeObjectsInArray:new];

Note however that a dictionary or a set would come more natural with this kind of data.

Georg Fritzsche