寫一個演示類 繼承于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中我們明明發(fā)現(xiàn)了下面的接口啊
- (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協(xié)議的類 的一個方法,如果沒有實現(xiàn),會拋出一個異常谒获。
由于我們調(diào)用了copy方法,而copy方法最終會要求調(diào)用類方法copyWithZone:寻定, 而NSObject本身并沒有實現(xiàn)這個類方法精耐, 這個類方法是放在NSCopying協(xié)議中的, 雖然在上面的NSObject.h文件中向胡, 有提到NSObject有類方法copyWithZone:惊完, 其實這是一個誤導(dǎo), 對于NSObject, 雖然有+(id)copyWithZone: ,NSObject類本身卻并沒有實現(xiàn)這個類方法小槐, 它是要求子類去實現(xiàn)的, 子類如果要調(diào)用copy方法件豌, 那么子類就去遵循NSCopying協(xié)議控嗜, 然后就能正常調(diào)用了。
NSMutableCopying協(xié)議同理
@interface testClass : NSObject <NSCopying,NSMutableCopying>
-(id)copyWithZone:(NSZone *)zone {
testClass *newClass = [[testClass alloc]init];
newClass.testString = self.testString;
return newClass;
}