可能重複:
When to use NSInteger vs int?
Why is there is an NSInteger?int和NSInteger有什麼區別?
我們可以使用int
和NSInteger
互換?有沒有什麼具體的情況只能使用NSInteger
,而不是使用int
?
可能重複:
When to use NSInteger vs int?
Why is there is an NSInteger?int和NSInteger有什麼區別?
我們可以使用int
和NSInteger
互換?有沒有什麼具體的情況只能使用NSInteger
,而不是使用int
?
我們可以互換使用int和NSInteger嗎?
不。在Apple使用的LP64架構上,對於現代OS X可可,NSInteger是64位寬。這意味着如果你將一個NSInteger轉換爲一個int,那麼與NSNotFound比較可能會失敗。這裏有一個例子:
NSRange theRange = [@"foo" rangeOfString @"x"];
int location = theRange.location;
if (location == NSNotFound) // comparison is broken due to truncation in line above
{
// x not in foo
}
在我看來,你需要傳遞一個參數,以可可或接收來自可可的結果和文檔說,數據類型是NSInteger
你應該只使用NSInteger
。在所有其他情況下:
int
或long
。stdint.h
類型,例如int32_t
,int64_t
。intptr_t
或uintptr_t
我想說的指針大小的整數使用標準C99 uintptr_t的。 NSInteger的定義看起來足夠多雲,不能確定它保證有指針。
如果必須的話,在API使用它的地方使用NSInteger。但長期以來都會爲所有實際目的而做。
看着NSObjCRunTime,我並沒有真正理解當前定義的動機。可能有一個足夠大的整數類型,例如,一個NSArray中的項目的最大數量?
#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
不,使用'uintptr_t'或'intptr_t'指針大小的整數。 – alastair 2011-05-19 11:36:08
謝謝,我也是C++ - 98(在這種情況下錯了)。答案已調整。 – 2011-05-19 12:34:56
的可能的複製[當使用NSInteger的VS INT?](http://stackoverflow.com/questions/4445173/when-to-use-nsinteger-vs-int)[如何轉換NSInteger的到int](http://stackoverflow.com/questions/1752701/),或[爲什麼有一個NSInteger](http://stackoverflow.com/questions/5870867/),只有三[衆多](http:///stackoverflow.com/search?q=nsinteger+int)。 – 2011-05-19 18:23:09