苹果系列:跨平台编译的宏定义选择(区分ios和mac)

本文介绍了如何在iOS和OSX开发中正确选择使用UIView或NSView的方法。通过检查特定宏,确保代码能够准确地针对不同平台进行编译和运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大意:

光用TARGET_OS_MAC并不能够区分ios和mac,需要像这样:

#if TARGET_OS_IPHONE
#define VIEW_CLASS UIView
#elif TARGET_OS_MAC
#define VIEW_CLASS NSView
#endif

先检查TARGET_OS_IPHONE 这个宏,在ios下(无论真机还是模拟器)该宏被定义;若未定义该宏则检查TARGET_OS_MAC。



原文如下:

Yesterday, I was messing around building shared NSLayoutConstraint code to be used across iOS and OS X. I put in a few #if TARGET_OS_MAC directives, assuming they'd just work.

They didn't.

Turns out that you should always check for TARGET_OS_IPHONE first, before TARGET_OS_MAC because the latter is true on the iPhone but the former is not on OS X.

Here are some of the most common checks suggested to me yesterday as I messed with this dilemma.

  • #if TARGET_OS_MAC
  • #if TARGET_OS_IPHONE
  • #if TARGET_IPHONE_SIMULATOR
  • #if TARGET_OS_EMBEDDED
  • #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  • #if defined(__IPHONE_OS_MIN_VERSION_REQUIRED)

And here are the results of running them on the Simulator, iPhone device and OS X:

SIMULATOR
Target OS Mac
Target OS iPhone
No Target OS Embedded
Target iPhone Simulator
Mac OS X Version Min Required is NOT defined
iPhone OS X Version Min Required is NOT defined

PHONE
Target OS Mac
Target OS iPhone
Target OS Embedded
No Target iPhone Simulator
Mac OS X Version Min Required is NOT defined
iPhone OS X Version Min Required is NOT defined

OS X
Target OS Mac
No Target OS iPhone
No Target OS Embedded
No Target iPhone Simulator
Mac OS X Version Min Required is defined
iPhone OS X Version Min Required is NOT defined

Since I was most interested in determining whether to use NSBox/NSView vs UIView, my solution ended up looking like this:

#if TARGET_OS_IPHONE
#define VIEW_CLASS UIView
#elif TARGET_OS_MAC
#define VIEW_CLASS NSView
#endif

This approach ensured that the iPhone platform triggered first, and then the second check mandated OS X. This created definitions that allowed my code to successfully compile and execute cross-platform.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值