如何复制目标c中的对象 [英] How to copy an object in objective c

查看:128
本文介绍了如何复制目标c中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要深度复制具有自己的对象的自定义对象。我一直在阅读,有点困惑,如何继承NSCopying和如何使用NSCopyObject。有人可以帮我吗?感谢您阅读!

I need to deep copy a custom object that has objects of its own. I've been reading around and am a bit confused as to how to inherit NSCopying and how to use NSCopyObject. Could someone help me out? Thanks for reading!

推荐答案

与参考类型一样,有复制的两个概念。我相信你知道他们,但是为了完整性。

As always with reference types, there are two notions of "copy". I'm sure you know them, but for completeness.


  1. 一个按位复制。在这里,我们只是复制位的内存位 - 这是NSCopyObject的作用。几乎总是,这不是你想要的。对象具有内部状态,其他对象等,并且经常假设它们是唯一保存对该数据的引用。按位复制会破坏此假设。

  2. 深层的逻辑副本。在这里,我们做一个对象的副本,但没有实际做它一点一点 - 我们想要一个行为相同的对象的所有意图和目的,但不是(必然)原始的内存相同的克隆 - Objective C手册调用这样一个对象功能独立从它的原始。因为使这些智能副本的机制因类而异,我们要求对象本身执行它们。这是NSCopying协议。

您需要后者。如果这是你自己的对象之一,你需要简单地采用协议NSCopying和实现 - (id)copyWithZone:(NSZone *)zone。你可以随意做任何你想要的;虽然这个想法是你自己做一个真实的副本并返回。您在所有字段上调用copyWithZone,以进行深层复制。一个简单的例子是

You want the latter. If this is one of your own objects, you need simply adopt the protocol NSCopying and implement -(id)copyWithZone:(NSZone *)zone. You're free to do whatever you want; though the idea is you make a real copy of yourself and return it. You call copyWithZone on all your fields, to make a deep copy. A simple example is

@interface YourClass : NSObject <NSCopying> 
{
   SomeOtherObject *obj;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
  // We'll ignore the zone for now
  YourClass *another = [[YourClass alloc] init];
  another.obj = [obj copyWithZone: zone];

  return another;
}

这篇关于如何复制目标c中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆