2010-05-02 86 views
3

在標題中,定義這樣的:我可以安全地將UInt32存儲到NSUInteger中嗎?

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger; 
typedef unsigned long NSUInteger; 
#else 
typedef int NSInteger; 
typedef unsigned int NSUInteger; 
#endif 

所以確實一個UInt32的配合毫無問題成NSUInteger(一個unsigned int)? UInt32和unsigned int之間的區別在哪裏?

我假設unsigned long比unsigned int大?

回答

9

我想一個UInt32unsigned int之間的唯一區別是UInt32保證是32位長,而一個unsigned int技術上可以更短,如果你是一個< 32位操作系統上運行(說)。

但是,鑑於Mac和iPhone都是至少32位系統,使用unsigned intUInt32NSUInteger合理可互換是安全的。唯一的區別是NSUInteger可能是64位長的(在Mac上編譯x86_64時)。

至於你的問題unsigned longunsigned intUInt32被typedef定義一個unsigned long,再次表明它是安全的交替使用。 unsigned long保證至少與unsigned int一樣大。

1

您可以隨時在你的程序,以儘量減少意外的開始部分增加一些環境檢查代碼:

if (sizeof(NSUInteger) != sizeof(UInt32)) { 
    printf("Error: Wrong integer type size!\n"); 
    exit(0); 
} 
+0

這將在64位平臺上失敗,其中'的sizeof(NSUInteger)'返回8'的sizeof (UInt32)'返回4. – 2010-05-03 16:21:19

+0

所以你知道_when_ NSUInteger和UInt32不能被同等對待。 – ohho 2010-05-04 01:22:17

相關問題