ios - respondsToSelector: 和 conformsToProtocol:的区别

 喜生-Da 发布于 2022-10-29 14:03

首先,我的理解是:
(1)conformsToProtocol:@protocol( )是用来检查对象是否实现了指定协议类的方法;
(2)respondsToSelector:@selector( )用于判断某个类/实例(包括基类)中是否包含某个方法,仅仅判断方法名是否有和@selector(...)中的方法名一致的,而不关注该方法是否有实现,是这样吗???

我主要是对(2)有疑惑,产生疑惑的原因是:
// 首先定义一个分类
// @interface NSArray (MutableDeepCopy)
// - (NSMutableArray *)mutableDeepCopyOfArray;
// @end

@implementation NSArray (MutableDeepCopy)

// - (NSMutableArray *)mutableDeepCopyOfArray {

NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[self count]];
for (int i = 0; i < [self count]; i++) {
    id oneValue = [self objectAtIndex:i];
    id oneCopy = nil;
    if ([oneValue respondsToSelector:@selector(mutableDeepCopyOfArray)]) {
        oneCopy = [oneValue mutableDeepCopyOfArray];
    }
    else if ([oneValue respondsToSelector:@selector(mutableCopy)]) {
        oneCopy = [oneValue mutableCopy];
    }

    if (oneCopy == nil) {
        oneCopy = [oneValue copy];
    }
    [newArray addObject:oneCopy];
}
return newArray;

}
@end

// - (void)touchesBegan:(NSSet> )touches withEvent:(UIEvent *)event
{

NSMutableArray *arr = [[NSMutableArray alloc]  initWithCapacity:12];
NSNumber *Num = [NSNumber  numberWithInteger:12345];
[arr  addObject:Num];
NSMutableArray *arr2 = [arr  mutableDeepCopyOfArray];

}

// 当数组中包含了NSNumber这种类型时,使用该分类方法执行深拷贝时,会报错;
错误很常见,很好理解,如下:
-[__NSCFNumber mutableCopyWithZone:]: unrecognized selector sent to instance 0xb000000000004d23

当我把 else if ([oneValue respondsToSelector:@selector(mutableCopy)]) 换成
else if ([oneValue conformsToProtocol:@protocol(NSMutableCopying)])时,程序正常执行,不报错;

所以,我觉得, respondsToSelector:@selector(mutableCopy),仅仅是从调用对象(或其父类)中,寻找是否有方法名为mutableCopy的方法,只要找到该方法就返回YES,并不强调一定要有mutableCopy方法的实现;而且恰好NSObject中有mutableCopy方法的声明,所以恰好能返回YES,但程序在执行后,崩溃了,因为mutableCopy方法没有实现,即mutableCopyWithZone:方法没有实现;

1 个回答
  • conformsToProtocol 是检测一个类是不是遵从某个协议,跟该类是不是实现了该协议的方法没什么关系(当然协议里声明称 required 的方法必须得实现)。

    respondsToSelector 是检测一个类或者其父类能不能响应某个消息。以你的例子里,NSObject 是可以响应 mutableCopy 消息的,NSNumber 是 NSObject 的子类,所以 respondsToSelector 返回 true 是没有问题的。respondsToSelector 并不是只检查了方法名,不是有方法声明但是没有实现也可以。它是要求必须要有实现的。 NSObject 类里是有 mutableCopy 方法的实现的,如文档里所说:
    Returns the object returned by mutableCopyWithZone:.
    This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for mutableCopyWithZone:.

    所以我们可以猜测一下, NSObject 的 mutableCopy 方法就是去调用 mutableCopyWithZone 并返回结果,如果该类没有实现 mutableCopyWithZone 方法,则抛出异常。

    你上面的程序崩溃了,并不是因为 mutableCopy 方法没有被实现, 也不是说 respondsToSelector 返回的结果“不准确“,其实是在意料之内的。

    2022-10-31 00:10 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有