简体   繁体   English

iPhone:如何同步2个NSMutableArrays的内容?

[英]iphone: how can i synchronize the contents of 2 NSMutableArrays?

I currently have an NSMutableArray which stores a collection of Video objects. 我目前有一个NSMutableArray,用于存储Video对象的集合。

Each Video object has an ID and TITLE. 每个视频对象都有一个ID和TITLE。

I also have another NSMutableArray of video objects generated from parsing an XML API call. 我还具有另一个NSMutableArray视频对象,这些视频对象是通过解析XML API调用生成的。

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? Objective-C是否定义了执行此操作的任何方法? If not, is there a special algorithm I can implement? 如果没有,我可以实现一种特殊的算法吗?

(Personally, I'd rather not loop through each and every item in both lists) (个人而言,我不想遍历两个列表中的每个项目)

Supposing you are only adding and deleting videos you can have two NSMutableDictionaries, one for deleting and the other for adding videos. 假设您仅添加和删除视频,则可以有两个NSMutableDictionaries,一个用于删除,另一个用于添加视频。 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. 当添加视频时,您将添加一个条目到ADDDictionary中,当您删除一个视频时,首先要检查它是否在ADDDictionay中显示为条目,如果删除,则将其添加到DELDictionary中。

You could use -removeObjectsInArray: to get the differences if you implemented isEqual: and hash sensibly: 如果实现了isEqual: -removeObjectsInArray:并且可以合理地进行hash则可以使用-removeObjectsInArray:获得差异:

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. 但是请注意,此类数据会使字典或集合更加自然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM