How should I declare a long in Objective-C? Is NSInteger appropriate?

后端 未结 5 762

I see NSInteger is used quite often and the typedef for it on the iPhone is a long, so technically I could use it when I am expect int(64) values.

5条回答
  •  盖世英雄少女心
    2021-01-12 12:29

    Integer Data Types Sizes

    • short - ILP32: 2 bytes; LP64: 2 bytes

    • int - ILP32: 4 bytes; LP64: 4 bytes

    • long - ILP32: 4 bytes; LP64: 8 bytes

    • long long - ILP32: 8 bytes; LP64: 8 bytes

    It may be useful to know that:

    The compiler defines the __LP64__ macro when compiling for the 64-bit runtime.

    NSInteger is a typedef of long so it will be 32-bits in a 32-bit environment and 64-bits in a 64-bit environment.

    When converting to 64-bit you can simply replace all your ints and longs to NSInteger and you should be good to go.

    Important: pay attention to the alignment of data, LP64 uses natural alignment for all Integer data types but ILP32 uses 4 bytes for all Integer data types with size equal to or greater than 4 bytes.

    You can read more about 32 to 64 bit conversion in the Official 64-Bit Transition Guide for Cocoa Touch.

    Answering you questions:

    How should I declare a long in Objective-C? Is NSInteger appropriate?

    You can use either long or NSInteger but NSInteger is more idiomatic IMHO.

    But should I be more explicit and use something like int64_t or long directly?

    If you expect consistent 64-bit sizes neither long nor NSInteger will do, you'll have to use int64_t (as Wevah said).

    What would be the downside of just using long?

    It's not idiomatic and you may have problems if Apple rolls out a new architecture again.

提交回复
热议问题