Class clazz = [NSString class]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:@"" forKey:clazz];
今天看到相关代码,跟同事讨论了一下,为什么
Class
可以作为NSMutableDictionary
的key
,而不会发生如下崩溃?*** 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:]
这时发现执行了一个对
key
的copy
操作,也是符合预期的。后来才发现原来官方文档已经说明得很详细了。
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...