如何检测设备是否为 iOS 8.3 中的 iPad?

How can I detect if device is an iPad in iOS 8.3?

我们将 SDK 更新到 iOS 8.3,突然间,我们的 iPad 检测方法无法正常工作:

+ (BOOL) isiPad
{
#ifdef UI_USER_INTERFACE_IDIOM
    return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
#endif
    return NO;
}

永远不会进入 ifdef 块,因此 return NO; 始终是 运行。 如何在不使用 UI_USER_INTERFACE_IDIOM() 的情况下检测设备是否为 iPad?


我正在使用:

8.2 UserInterfaceIdiom()中是

#define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)

8.3UserInterfaceIdiom()

static inline UIUserInterfaceIdiom UI_USER_INTERFACE_IDIOM() {
    return ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ?
            [[UIDevice currentDevice] userInterfaceIdiom] :
            UIUserInterfaceIdiomPhone);
}

所以 #ifdef UI_USER_INTERFACE_IDIOM8.3

中总是假的

请注意 header 表示

The UI_USER_INTERFACE_IDIOM() function is provided for use when deploying to a version of the iOS less than 3.2. If the earliest version of iPhone/iOS that you will be deploying for is 3.2 or greater, you may use -[UIDevice userInterfaceIdiom] directly.

因此建议您重构为

+ (BOOL) isiPad
{
    static BOOL isIPad = NO;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        isIPad = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
    });
    return isIPad;
}