关于使用Copy崩溃的问题

写一个演示类 继承于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;
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容