【问题标题】:Checking whether UI_USER_INTERFACE_IDIOM exists at runtime在运行时检查 UI_USER_INTERFACE_IDIOM 是否存在
【发布时间】:2010-04-16 15:53:01
【问题描述】:

我正在开发一个应该能够在 iPad 和 iPhone 上运行的通用应用程序。 Apple iPad 文档说使用UI_USER_INTERFACE_IDIOM() 来检查我是在iPad 还是iPhone 上运行,但我们的iPhone 是3.1.2 并且不会定义UI_USER_INTERFACE_IDIOM()。因此,此代码中断:

//iPhone should not be flipped upside down. iPad can have any
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  return YES; //are we on an iPad?
 } else {
  return interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
 }
}

在 Apple 的 SDK Compatibility Guide 中,他们建议执行以下操作来检查该功能是否存在:

//iPhone should not be flipped upside down. iPad can have any
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 if(UI_USER_INTERFACE_IDIOM() != NULL &&
  UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  return YES; //are we on an iPad?
 } else {
  return interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
 }
}

这可行,但会导致编译器警告:“指针和整数之间的比较。”在四处挖掘之后,我发现我可以通过以下转换为(void *) 使编译器警告消失:

//iPhone should not be flipped upside down. iPad can have any
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 if((void *)UI_USER_INTERFACE_IDIOM() != NULL &&
  UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  return YES; //are we on an iPad?
 } else {
  return interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
 }
}

我的问题是:这里的最后一个代码块可以/可接受/标准做法吗?我找不到其他人通过快速搜索来做这样的事情,这让我想知道我是否错过了一个陷阱或类似的事情。

谢谢。

【问题讨论】:

  • UI_USER_INTERFACE_IDIOM 是一个编译时宏。它在运行时不“存在”
  • 这不会让这个问题不值得投票。

标签: iphone objective-c ipad function-pointers backwards-compatibility


【解决方案1】:

您需要针对 3.2 SDK 为 iPad 构建应用程序。因此它将正确构建,并且 UI_USER_INTERFACE_IDIOM() 宏仍然可以工作。如果您想知道如何/为什么,请在文档中查找 - 它是一个#define,编译器会理解它并编译成可以在 3.1(等)上正确运行的代码。

【讨论】:

  • 好的,是的,这行得通。我弄清楚发生了什么:我最初设置项目以构建两个不同的应用程序,然后切换到使用通用应用程序。第一个块中的代码是针对旧方式的,显然我在针对 3.2 构建时从未运行过它。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
相关资源
最近更新 更多