> For the complete documentation index, see [llms.txt](https://coderiding.gitbook.io/dgjj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coderiding.gitbook.io/dgjj/hu-lian-wang-gai-nian/qian-duan/ios/zi-ding-yi-de-lei-ru-he-shi-xian-copy.md).

# 自定义的类，如何实现copy

* 遵守NSCopying或者NSMutableCopying
* 而遵守上面两个协议，只需要实现一个方法

```
// 实现 copyWithZone 方法
// 参数 zone 基本不用，它的意思是指定该方法从始至终都在某一个区域分配内存 
- ( id ) copyWithZone: ( NSZone * ) zone{  
　　 // 方法内部进行以下操作  
　　 // （ 1 ）实例化对象  
　　 A* a = [ A alloc ] init ]; 
	 // 一般正规写法是[[ self.class alloc ] init ]   因为这样子类也可以复用该方法  
　　 // （ 2 ）给属性赋值  
　　 a.xx = xx;  
　　 // （ 3 ）返回新对象  
　　 return a;  
} 
```

## 自定义类例子

```
//1. 遵守 NSCopying 协议  
@interface Teacher : NSObject<NSCopying>  
@property ( nonatomic , copy ) NSString* name ;  
//2. 实现 copyWithZone 方法；  
- ( id ) copyWithZone: ( NSZone * ) zone ;  
@end  

@implementation Teacher  
// 实现 copyWithZone 方法  
- ( id ) copyWithZone: ( NSZone * ) zone  
{  
    Teacher* teacher = [[ self.class alloc ] init ];  
    teacher.name = self.name ;  
    return teacher ;  
} 
```
