我正在为一个 iPhone 应用程序进行简单的 OCUnit 测试,只是想断言应用程序委托是我期望的类的一个实例。我没想到这个测试会很有用,但结果却揭示了我对 Objective C 的误解。
我首先得到对代表的引用。然后我记录返回的类名。就我而言,输出正确显示“应用程序委托的类名是 CalculatorAppDelegate”。
但是,下一行的断言失败了,我不明白为什么。
- (void)testAppDelegate
{
id appDelegate = [[UIApplication sharedApplication] delegate];
NSLog(@"app delegate's class name is %@", NSStringFromClass([appDelegate class]));
NSLog(@"is it kind? %i", [appDelegate isKindOfClass:[CalculatorAppDelegate class]]);
NSLog(@"is it member? %i", [appDelegate isMemberOfClass:[CalculatorAppDelegate class]]);
NSLog(@"class == class %i", [appDelegate class] == [CalculatorAppDelegate class]);
STAssertTrue([appDelegate isKindOfClass:[CalculatorAppDelegate class]], @"wtf");
}
什么情况下会导致 NSStringFromClass() 返回正确的类名,而 isKindOfClass 返回 false?
2011-03-19 15:51:13.864 Calculator[40092:207] app delegate's class name is CalculatorAppDelegate
2011-03-19 15:51:13.864 Calculator[40092:207] is it kind? 0
2011-03-19 15:51:13.865 Calculator[40092:207] is it member? 0
2011-03-19 15:51:13.865 Calculator[40092:207] class == class 0
/Users/pohl/Developer/FoundationCalculator/CalculatorTests/CalculatorBrainTests.m:37: error: -[CalculatorBrainTests testAppDelegate] : "[appDelegate isKindOfClass:[CalculatorAppDelegate class]]" should be true. wtf
Test Case '-[CalculatorBrainTests testAppDelegate]' failed (0.002 seconds).