OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 %i 格式化 NSUInteger [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:41
标题: ios - 使用 %i 格式化 NSUInteger

我正在查看一份前雇员代码,其中出现了大约 20 个警告:

Values of type 'NSUInteger' should not be used as format arguments; add an explicit cast to 'unsigned long' instead

出现这种情况的部分代码是:

NSUInteger Length;

与:

- (NSString *) description {

    // If no value was given, display type
    if([Value length] == 0)
    {
        NSString *type = @"";

        switch (Type) {
            case DTCompType_Year: type = @"year";
                break;
            case DTCompType_Month: type = @"month";
                break;            
            case DTCompType_Day: type = @"day";
                break;            
            case DTCompType_Hour: type = @"hour";
                break;            
            case DTCompType_Minute: type = @"minute";
                break;            
            case DTCompType_Second: type = @"second";
                break;            
            case DTCompType_Meridiem: type = @"meridiem";
                break;            
            case DTCompType_MonthName: type = @"month_name";
                break;
            case DTCompType_DayOfTheWeek: type = @"day_of_the_week";
                break;
            case DTCompType_Undefined: type = @"undefined";
                break;            
        }

        return Length == 0 ? [NSString stringWithFormat"[%@]", type] : 
        [NSString stringWithFormat"[%@:%i]", type, Length];
    }

在苹果文档中找不到 %i

Apple's Documentation

我以前从未使用过 Objective-C,现在我必须更新这个应用程序。我知道这需要成为一个无符号长,但我不想在不知道为什么的情况下开始改变事情。该应用程序可以正常工作,那么将这些更改为 unsigned long 是否有任何内在后果?甚至将格式说明符从 %i 更改为 %lu

根据我的阅读,这可能是平台的问题。 (32 位与 64 位)

这是为 iOS7 中的 iPad 2 开发的,我们刚刚将 SDK 升级到 iOS8。

我发现了这个帖子: NSUInteger should not be used in format strings? 这给了我一些指导,但我需要更多说明。



Best Answer-推荐答案


%i 等价于 %d。从技术上讲,你应该一直在使用 %u 。正如您所怀疑的,问题是 32 位与 64 位; NS[U]Integer 在 32 位版本上是 [unsigned] int,但在 64 位版本上是 [unsigned] long。因为 iPhone 是 little-endian,所以只要 %i/d/u 是最后指定的格式,它就会“工作”,但它仍然是错误的。您应该将参数转换为格式说明符期望的类型 (int/long/unsigned/unsigned long ),正如警告消息告诉您的那样。

来自 :

#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

关于ios - 使用 %i 格式化 NSUInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26871770/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4