我正在做一个 iOS5+ 项目(xcode 4.4.1 SDK 5.1)
我在单元测试中有这段代码:
[_appDelegate application:nil didFinishLaunchingWithOptions:nil];
UITabBarController *tabBarController = (UITabBarController*)_appDelegate.window.rootViewController;
NSArray *viewControllers = [tabBarController viewControllers];
UINavigationController *nc_1 = [viewControllers objectAtIndex:0];
UIViewController *vc_1 = nc_1.topViewController;
STAssertTrue([vc_1 isKindOfClass:[ScheduleViewController class]]==YES, @"UITabBarController first tab should be a ScheduleViewController class");
如果我运行测试,测试会失败。
所以我用调试器检查:
(lldb) po [ScheduleViewController class]
(id) $1 = 0x00142b04 ScheduleViewController
(lldb) po vc_1
(UIViewController *) $2 = 0x11a32dc0 <ScheduleViewController: 0x11a32dc0>
(lldb) print (BOOL) [vc_1 isKindOfClass:(Class)[ScheduleViewController class]]
(BOOL) $4 = YES
(lldb) po [vc_1 class]
(id) $5 = 0x00142b04 ScheduleViewController
(lldb)
在 application:didFinishLaunchingWithOptions: 中,我创建了一个 ScheduleViewController 并将其用作导航 Controller 的 rootController。调试器说它是正确的。 我不明白上面的断言有什么问题。
有人对此有想法吗?
更新
断言的第一个实现是:
STAssertTrue([vc_1 isKindOfClass:[ScheduleViewController class]], @"UITabBarController first tab should be a ScheduleViewController class");
断言以同样的方式失败。
更新 2
按照评论中的建议,我尝试在断言之前添加这段代码:
BOOL vcBool = [vc_1 isKindOfClass:[ScheduleViewController class]];
使用调试器我看到:
(lldb) print (BOOL) [vc_1 isKindOfClass:(Class)[ScheduleViewController class]]
(BOOL) $1 = YES
(lldb) print (BOOL) vcBool
(BOOL) $2 = NO
(lldb)
更新 3
我按照评论中的建议在断言之前添加了这一行:
NSLog(@"vc_1=%@ class=%@", vc_1, NSStringFromClass([vc_1 class]));
从调试控制台:
vc_1=<ScheduleViewController: 0x993bdb0> class=ScheduleViewController
最佳答案
我找到了解决方案。
它与@vacawama 在评论中链接的帖子中提出的解决方案相反。我在测试目标中也有应用程序目标的所有 *.m 源。当我在寻找 isKindOfClass 问题的解决方案时,我注意到在测试 session 开始时控制台上有很多警告。警告是这样的:
Class AClass is implemented in both /Application Support/iPhone Simulator/5.0/Applications/7FC68A9C-4F2C-4A30-85AD-87D8ABA7A275/App.app/App and /Developer/Xcode/DerivedData/App-fvbgaqbdupuoodgquxhlwbudpsin/Build/Products/Debug-iphonesimulator/App.octest/AppTests. One of the two will be used. Which one is undefined.
我从测试目标中删除了应用程序的所有 .m 文件。
现在 isKindOfClass 按预期工作。
感谢大家的支持。
关于objective-c - isKindOfClass 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12386189/