NSInteger计算时间4?

时间:2011-03-22 22:45:57

标签: ios increment nsinteger

我不明白为什么这个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);

2 个答案:

答案 0 :(得分:11)

因为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

答案 1 :(得分: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;