簡體   English   中英

isKindOfClass無法按預期工作

[英]isKindOfClass doesn't work as expected

我正在開發一個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) 

在應用程序中:didFinishLaunchingWithOptions:我創建一個ScheduleViewController,我將它用作導航控制器的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問題的解決方案時,我注意到在測試會話開始時控制台上發出了很多警告。 警告是這樣的:

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按預期工作。

感謝大家的支持。

您不應該直接將BOOL值與YES進行比較。 這可能會導致你的斷言出現問題。 以下是該問題的背景參考: http//mobiledevelopertips.com/objective-c/of-bool-and-yes.html

使用NSStringFromClass將類名轉換為字符串將避免使用isKindOfClass ...示例:

if ([NSStringFromClass([AViewController class]) isEqualToString:NSStringFromClass([BViewController class])])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM