当前位置:  开发笔记 > IOS > 正文

为什么resolveInstanceMethod:有时调用两次

如何解决《为什么resolveInstanceMethod:有时调用两次》经验,为你挑选了0个好方法。

最近,我正在研究Objective-C中的运行时.

我创建了一个名为的类TO:

@interface TO : NSObject
@end

#import "TO.h"

@implementation TO

- (id)forwardingTargetForSelector:(SEL)aSelector {
    NSLog(@"%@ sel: %@", NSStringFromSelector(_cmd), NSStringFromSelector(aSelector));
    return nil;
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    NSLog(@"%@ sel: %@", NSStringFromSelector(_cmd), NSStringFromSelector(aSelector));
    return NO;
}

+ (BOOL)resolveClassMethod:(SEL)sel {
    NSLog(@"%@ sel: %@", NSStringFromSelector(_cmd), NSStringFromSelector(sel));
    return NO;
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    NSLog(@"%@ sel: %@", NSStringFromSelector(_cmd), NSStringFromSelector(sel));
    return NO;
}

+ (IMP)instanceMethodForSelector:(SEL)aSelector {
    NSLog(@"%@ sel: %@", NSStringFromSelector(_cmd), NSStringFromSelector(aSelector));
    return nil;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

@end

然后,我在某个地方调用一个未经识别的选择器:

TO *to = [TO new];
id res = [(NSString *)to uppercaseString];

随后,我得到了以下输出:

2015-12-22 22:27:04.319 OCDemo[81920:7728539] resolveInstanceMethod: sel: uppercaseString
2015-12-22 22:27:04.320 OCDemo[81920:7728539] forwardingTargetForSelector: sel: uppercaseString
2015-12-22 22:27:04.320 OCDemo[81920:7728539] resolveInstanceMethod: sel: uppercaseString
2015-12-22 22:27:04.320 OCDemo[81920:7728539] -[TO uppercaseString]: unrecognized selector sent to instance 0x7fdd3ad120a0
2015-12-22 22:27:04.322 OCDemo[81920:7728539] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TO uppercaseString]: unrecognized selector sent to instance 0x7fdd3ad120a0'

如我们所见,resolveInstanceMethod:被称为两次.

但是,如果我-[description]先打电话:

TO *to = [TO new];
[to description];
id res = [(NSString *)to uppercaseString];

然后,输出将是:

2015-12-22 22:58:50.458 OCDemo[82137:7813436] resolveInstanceMethod: sel: uppercaseString
2015-12-22 22:58:50.459 OCDemo[82137:7813436] forwardingTargetForSelector: sel: uppercaseString
2015-12-22 22:58:50.459 OCDemo[82137:7813436] -[TO uppercaseString]: unrecognized selector sent to instance 0x7f9bcad59960
2015-12-22 22:58:50.461 OCDemo[82137:7813436] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TO uppercaseString]: unrecognized selector sent to instance 0x7f9bcad59960'

这个时间resolveInstanceMethod:只召唤一次.

有人可以解释一下吗?

推荐阅读
爱唱歌的郭少文_
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有