I was playing with a simple OCUnit test for an iPhone app, and just wanted to assert that the app delegate was an instance of the class that I expected it to be. I didn't expect this test to be very useful, but it turned out to reveal a misunderstanding that I have regarding Objective C.
I first get a reference to the delegate. Then I log the class name of what comes back. In my case, the output correctly says "app delegate's class name is CalculatorAppDelegate".
However, the assertion on the next line fails, and I don't understand why.
- (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");
}
What circumstances could cause NSStringFromClass() to return the correct class name, while isKindOfClass returns 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).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…