NSDate isMemberOfClass:[NSDate class]返回false? [英] NSDate isMemberOfClass: [NSDate class] returns false?
问题描述
这很奇怪。以下if语句失败。可能出错?
NSDate * date = [NSDate date];
if([date isMemberOfClass:[NSDate class]]){
//未执行。
}
code> NSArray , NSDictionary
, NSString
和
NSData
是类集群。这个概念在
文档,这意味着您不会得到该类的直接实例
。
由于要处理的数据的多样性,类具有内部的
专用子类;当你创建一个实例时,将
确定哪些内部子类是最好的选项,
你的对象将是该子类的实例(不是 NSData
本身)。
在这种情况下,如果你需要检查,使用 isKindOfClass: code>这将
也为真子类。
NSDate * date = [NSDate date] ;
pre>
if([date isKindOfClass:[NSDate class]]){
/ * ... * /
}
编辑:
另一个例子,调用NSStringFromClass([obj class])
在这些对象中:NSData * data = [NSData data];
NSData * str_data = [@stringdataUsingEncoding:NSUTF8StringEncoding];
NSNumber * n_bool = [NSNumber numberWithBool:YES];
NSNumber * n_int = [NSNumber numberWithInt:42];
NSArray * array = [NSArray array];
结果:
_NSZeroData
NSConcreteMutableData
__NSCFBoolean
__NSCFNumber
__NSArrayI
this is bizarre. The following if statement is failing. What could be wrong?
NSDate *date = [NSDate date]; if ([date isMemberOfClass: [NSDate class]]) { // Not executed. }
解决方案It happens that classes like
NSArray
,NSDictionary
,NSString
andNSData
are class clusters. This concept is explained better in the documentation, and it means that you will not get a direct instance for that class.Due to the variety of "data" to be handled, the class has internal specialised subclasses; and when you create an instance it will be determined which of these internal subclasses is the best option, and your object will then be an instance of that subclass (not of
NSData
itself).In this case, if you need to check that, use
isKindOfClass:
which will be true for subclasses as well.NSDate *date = [NSDate date]; if ([date isKindOfClass: [NSDate class]]) { /* ... */ }
Edit: Just as an additional example, calling
NSStringFromClass([obj class])
in these objects:NSData * data = [NSData data]; NSData * str_data = [@"string" dataUsingEncoding:NSUTF8StringEncoding]; NSNumber * n_bool = [NSNumber numberWithBool:YES]; NSNumber * n_int = [NSNumber numberWithInt:42]; NSArray * array = [NSArray array];
Results in:
_NSZeroData NSConcreteMutableData __NSCFBoolean __NSCFNumber __NSArrayI
这篇关于NSDate isMemberOfClass:[NSDate class]返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!