Class 作为 NSMutableDictionary 的 key

Tags
iOS
Date
Apr 28, 2021
Class clazz = [NSString class]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:@"" forKey:clazz];
今天看到相关代码,跟同事讨论了一下,为什么Class可以作为NSMutableDictionarykey,而不会发生如下崩溃?
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController copyWithZone:]: unrecognized selector sent to instance 0x7ffad4d1ba40'
首先,一个Class也是一个NSObject,即是一个对象。
NSLog(@"isKindOfClass %d", [clazz isKindOfClass:[NSObject class]]); // isKindOfClass 1
然后,这个对象是有遵循NSCopying协议的。
NSLog(@"conformsToProtocol %d", [clazz conformsToProtocol:@protocol(NSCopying)]); // conformsToProtocol 1
下一个符号断点+[NSObject copyWithZone:]
notion image
 
notion image
这时发现执行了一个对keycopy操作,也是符合预期的。
后来才发现原来官方文档已经说明得很详细了。
 
👉
This method exists so class objects can be used in situations where you need an object that conforms to the NSCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.
 

Loading Comments...