【问题标题】:NSInteger counts times 4?NSInteger 计数乘以 4?
【发布时间】:2011-07-20 21:43:26
【问题描述】:

我不明白为什么这个 NSInteger 计数器会精确地增加到数据库行的真实值的 4 倍。也许这很愚蠢,但我真的不明白......

到目前为止谢谢:)

NSInteger *i;
i = 0;

for ( NSDictionary *teil in gText ) {

    //NSLog(@"%@", [teil valueForKey:@"Inhalt"]);

    [databaseWrapper addEntry:[teil valueForKey:@"Inhalt"] withTyp:[teil valueForKey:@"Typ"] withParagraph:[teil valueForKey:@"Paragraph"]];

    i+=1;
}

NSLog(@"Number of rows created: %d", i);

【问题讨论】:

    标签: ios increment nsinteger


    【解决方案1】:

    i 未声明为 NSInteger,它声明为指向 NSInteger 的指针。

    由于NSInteger是4个字节,当你加1时,指针实际上增加了1个NSInteger,也就是4个字节。

    i = 0;
    ...
    i += 1; //Actually adds 4, since sizeof(NSInteger) == 4
    ...
    NSLog(@"%d", i); //Prints 4
    

    之所以会出现这种混淆,是因为NSInteger 不是对象,因此您不需要声明指向它的指针。将您的声明更改为预期行为:

    NSInteger i = 0;
    

    【讨论】:

    • "i 没有被声明为 NSInteger,它被声明为 NSInteger。"呃……什么?
    【解决方案2】:

    因为 i 是一个指针,并且您正在递增指针值,该值很可能以 4 为步长(NSInteger 指针的大小)。只需删除指针 * 引用就可以了。

    NSInteger i = 0;
    
    for ( NSDictionary *teil in gText ) {
    

    理论上你可以通过艰难的方式做到这一点。

    NSInteger *i;
    *i = 0;
    for ( NSDictionary *teil in gText ) {
    ...
    *i = *i + 1;
    ...
    

    来自: Foundation Data Types Reference

    #if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
    typedef long NSInteger;
    #else
    typedef int NSInteger;
    #endif
    

    【讨论】:

    • 啊,所以 NSInteger 不是像所有其他 NSS 一样的常规 Object...,它是原始类型?
    • 是的,实际上这很有趣,因为它是 long 或 int 的 typedef。我将包含文档中的片段。
    • 嗯,好像让 64 位更直观...对我来说很好,谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多