写一个演示类 继承于NSObject
#import <Foundation/Foundation.h>
@interface testClass : NSObject
@end
#import "testClass.h"
@implementation testClass
@end
//实例化一个实例
testClass *test = [[testClass alloc] init];
//testClass *tempOne = [test copy];// crash 崩溃了
//NSLog(@"%@",tempOne);
**reason: '-[testClass copyWithZone:]: unrecognized selector sent to instance 0x7fb2517107c0'**
testClass *tempTwo = [test mutableCopy];// crash 崩溃了
NSLog(@"%@",tempTwo);
**reason: '-[testClass mutableCopyWithZone:]: unrecognized selector sent to instance 0x7fbfa3620f30'**
但是在NSObject.h中我们明明发现了下面的接口啊
- (id)copy;
- (id)mutableCopy;
+ (id)copyWithZone:(struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
+ (id)mutableCopyWithZone:(struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
文档的解释
This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copyWithZone:.
copyWithZone: 是遵守NSCopying协议的类 的一个方法,如果没有实现,会抛出一个异常。
由于我们调用了copy方法,而copy方法最终会要求调用类方法copyWithZone:, 而NSObject本身并没有实现这个类方法, 这个类方法是放在NSCopying协议中的, 虽然在上面的NSObject.h文件中, 有提到NSObject有类方法copyWithZone:, 其实这是一个误导, 对于NSObject, 虽然有+(id)copyWithZone: ,NSObject类本身却并没有实现这个类方法, 它是要求子类去实现的, 子类如果要调用copy方法, 那么子类就去遵循NSCopying协议, 然后就能正常调用了。
NSMutableCopying协议同理
@interface testClass : NSObject <NSCopying,NSMutableCopying>
-(id)copyWithZone:(NSZone *)zone {
testClass *newClass = [[testClass alloc]init];
newClass.testString = self.testString;
return newClass;
}