iphone:我如何同步2个NSMutableArrays的内容?
我目前有一个 NSMutableArray,它存储视频对象的集合。
每个视频对象都有一个 ID 和 TITLE。
我还有另一个通过解析 XML API 调用生成的视频对象 NSMutableArray。
当用户点击“同步”按钮时,我希望系统能够计算出使两个列表同步所需的最少操作数(删除和添加视频)。
这样做的最佳方法是什么? Objective-C 是否定义了执行此操作的任何方法?如果没有,我可以实现特殊的算法吗?
(就我个人而言,我不想循环遍历两个列表中的每个项目)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您只添加和删除视频,您可以有两个 NSMutableDictionaries,一个用于删除,另一个用于添加视频。
当您添加视频时,您会在 ADDDictionary 中添加一个条目,当您删除一个视频时,您首先检查它是否在 ADDDictionary 中显示为条目,如果是,则将其删除,否则您会在 DELDictionary 中添加一个条目。
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.
您可以使用 < code>-removeObjectsInArray: 如果您明智地实现了
isEqual:
和hash
来获得差异:但请注意,将会出现字典或集合使用这种数据更自然。
You could use
-removeObjectsInArray:
to get the differences if you implementedisEqual:
andhash
sensibly:Note however that a dictionary or a set would come more natural with this kind of data.