如何深度复制NSIndexPath?

时间:2012-05-19 14:21:12

标签: objective-c nsindexpath

我想保存一份NSIndexPath对象供以后使用。然后,我想要覆盖原始对象。由于copy仅增加对象的保留计数,如何制作原始索引路径的深层副本?

...
NSIndexPath *originalIndexPath = [tappedIndexPath copy]; // need to make a deep copy here
tappedIndexPath = ...;
...
// need the original index path here

2 个答案:

答案 0 :(得分:2)

无论如何NSIndexPath是不可变的,副本是深还是浅都无关紧要。事实上,深层复制会浪费内存。

关于您的示例:对于您想要执行的操作,您根本不需要复制索引路径。当您将另一个索引路径对象分配给tappedIndexPath时(在第二行中),这根本不会影响originalIndexPath。在代码段的末尾,originalIndexPath仍将指向与之前完全相同的对象。

答案 1 :(得分:0)

你的问题并不完全清楚。如果你需要保存它以便以后在另一个类中使用,你应该尝试以下两种方法。

您无法直接在NSUserDefaults中保存NSIndexPath。但是,您可以使用NSKeyedArchive和NSKeyedUnarchiver来帮助您完成此任务。

http://gordiychuk.co.uk/2012/02/10/how-to-save-nsindexpath-to-nsuserdefaults/

我不确定您对NSIndexPath的确需要什么。我做到了这一点,我在创建我的UIViewController时通过init方法传递了NSIndexPath。我需要知道用户在另一个类中选择了哪一行。

例如:

- (id)initWithNibName:(NSString *)nibNameOrNil 
               bundle:(NSBundle *)nibBundleOrNil 
   initWithNSIdexPath:(NSIndexPath *)indexPath
{
    // Do something indexPath
}
相关问题