범용 iPhone 앱을 만들려고하는데 최신 버전의 SDK에서만 정의 된 클래스를 사용합니다. 프레임 워크는 이전 시스템에 존재하지만 프레임 워크에 정의 된 클래스는 존재하지 않습니다.
약한 링크를 사용하고 싶지만 함수 존재에 대한 런타임 검사에 대한 문서를 찾을 수있는 문서가 있습니다. 클래스가 존재하는지 어떻게 확인합니까?
답변:
흐름:
if #available(iOS 9, *)
if (@available(iOS 11.0, *))
if (NSClassFromString(@"UIAlertController"))
유산:
if objc_getClass("UIAlertController")
if (NSClassFromString(@"UIAlertController"))
if ([UIAlertController class])
역사적으로 특정 OS 버전이 아닌 기능 (또는 클래스 존재)을 확인하는 것이 권장되었지만 가용성 확인 이 도입 되었기 때문에 Swift 2.0에서는 제대로 작동하지 않습니다 .
대신 다음 방법을 사용하십시오.
if #available(iOS 9, *) {
// You can use UIStackView here with no errors
let stackView = UIStackView(...)
} else {
// Attempting to use UIStackView here will cause a compiler error
let tableView = UITableView(...)
}
Note: If you instead attempt to use objc_getClass()
, you will get the following error:
⛔️ 'UIAlertController' is only available on iOS 8.0 or newer.
if objc_getClass("UIAlertController") != nil {
let alert = UIAlertController(...)
} else {
let alert = UIAlertView(...)
}
Note that objc_getClass()
is more reliable than NSClassFromString()
or objc_lookUpClass()
.
if ([SomeClass class]) {
// class exists
SomeClass *instance = [[SomeClass alloc] init];
} else {
// class doesn't exist
}
See code007's answer for more details.
Class klass = NSClassFromString(@"SomeClass");
if (klass) {
// class exists
id instance = [[klass alloc] init];
} else {
// class doesn't exist
}
Use NSClassFromString()
. If it returns nil
, the class doesn't exist, otherwise it will return the class object which can be used.
This is the recommended way according to Apple in this document:
[...] Your code would test for the existence of [a] class using
NSClassFromString()
which will return a valid class object if [the] class exists or nil if it doesnʼt. If the class does exist, your code can use it [...]
Class
instance returned by NSClassFromString
(assign it to id
) and invoke selectors on that instance.
canImport
. Proposal
For new projects that uses a base SDK of iOS 4.2 or later, there is this new recommended approach which is to use the NSObject class method to check the availability of weakly linked classes at run time. i.e.
if ([UIPrintInteractionController class]) {
// Create an instance of the class and use it.
} else {
// Alternate code path to follow when the
// class is not available.
}
This mechanism uses the NS_CLASS_AVAILABLE macro, which is available for most framework in iOS (note there may be some framework that do not yet support the NS_CLASS_AVAILABLE - check the iOS release note for this). Extra setting configuration may also be needed that can be read in the Apple's documentation link provided above, however, the advantage of this method is that you get static type checking.
UIAlertController
while still supporting iOS 7. code007's answer is correct, but the extra configuration needed is to weakly link (set from Required
to Optional
) UIKit in your project (for this situation, at least).