• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 使用 %i 格式化 NSUInteger

[复制链接]
菜鸟教程小白 发表于 2022-12-12 12:41:18 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在查看一份前雇员代码,其中出现了大约 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap