以下代码片段为什么只打印blah3和blah4,而不是blah2?
isKindOfClass应该尊重继承关系,但它似乎未能做到这一点。
Obj-C:
使用Xcode 7.3.1,iOS 9.3。
isKindOfClass应该尊重继承关系,但它似乎未能做到这一点。
Obj-C:
NSDictionary *dict = [NSDictionary new];
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
if([dict isKindOfClass:[mutableDict class]]){
NSLog(@"blah"); //does not print (as expected)
}
if([mutableDict isKindOfClass:[dict class]]){
NSLog(@"blah2"); //does not print (unexpected!)
}
if([mutableDict isKindOfClass:[mutableDict class]]){
NSLog(@"blah3"); //prints
}
if([dict isKindOfClass:[dict class]]){
NSLog(@"blah4"); //prints
}
Swift:
var dict = NSDictionary()
var mutableDict = NSMutableDictionary()
if(dict.isKindOfClass(mutableDict.dynamicType)) {print("blah")}
if(mutableDict.isKindOfClass(dict.dynamicType)) {print("blah2")}
if(dict.isKindOfClass(dict.dynamicType)) {print("blah3")}
if(mutableDict.isKindOfClass(mutableDict.dynamicType)) {print("blah4")}
使用Xcode 7.3.1,iOS 9.3。
NSMutableDictionary
是NSDictionary
的子类,因此isKindOf
将返回true
,并且应该打印出blah2
。 - Alexander