I want to conform to the UIAlertController used in iOS 8 since UIAlertView is now deprecated. Is there a way that I can use this without breaking support for iOS 7? Is there some kind of if condition I can do to check for iOS 8 otherwise do something else for iOS 7 support?
I think a much better way to check if a class exists (since iOS 4.2) is:
if([ClassToBeChecked class]) {
// use it
} else {
// use alternative
}
In your case, that would be:
if ([UIAlertController class]) {
// use UIAlertController
} else {
// use UIAlertView
}
Objective C (as mentioned above)
if ([UIAlertController class]) {
// use UIAlertController
} else {
// use UIAlertView
}
Swift
if objc_getClass("UIAlertController") == nil {
// use UIAlertView
} else {
// use UIAlertController
}
Don't use if NSClassFromString("UIAlertController") == nil
It is not working because the signature for this method is func NSClassFromString(_ aClassName: String!) -> AnyClass!
Please see the answer of Erwan (below my answer) as I see it is the best.
--
You can check the iOS version to use appropriate control like this:
if (([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] == NSOrderedAscending)) {
// use UIAlertView
}
else {
// use UIAlertController
}
As others have already mentioned - always check whether a feature exists. I believe the safest approach is following:
if (NSClassFromString(@"UIAlertController")) {
// use UIAlertController
} else {
// use UIAlertView
}
With the obvious risk of entering a class name with a typo. :)
From documentation of NClassFromString:
[Returns] The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.
Availability iOS (2.0 and later)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With