respondsToSelector - not working

2019-07-12 08:38发布

问题:

I've read through like 10 posts, but haven't found what's wrong with my implementation.

This app was written in iOS 6 but updated to iOS7, so I want to offer support for both iOS6 and iOS7. But if I run an iOS7-only method on an iOS6 device, it breaks. So I thought of adding respondsToSelector, to check it has iOS7 on it, but for some reason, the if always returns false.

AppDelegate.m:

if ([[UINavigationBar appearance] respondsToSelector:@selector(shadowImage)])

if ([[UINavigationBar appearance] respondsToSelector:@selector(setShadowImage:)])

Can someone tell me what am I doing wrong?

Edit: I've tried with deployment target set to both iOS6 and iOS7, both cases return false.

Edit2: If I remove the if statement and call the method, it works as intended in iOS7.

回答1:

Instead of querying [UINavigationBar appearance] for the selector, just

[UINavigationBar instancesRespondToSelector:@selector(shadowImage)]

an alternative solution may be checking the iOS version

if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending)
    NSLog(@"iOS >= 7.0");