NSInteger 计数乘以 4?

发布于 2024-10-25 16:36:26 字数 419 浏览 2 评论 0原文

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

I don't understand why this NSInteger counter increments to exactly 4 times the true value of database rows. Maybe this is stupid but I really just don't get it...

Thanks so far :)

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随波逐流 2024-11-01 16:36:26

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

NSInteger i = 0;

for ( NSDictionary *teil in gText ) {

理论上你可以用困难的方式做到这一点。

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

从:
基础数据类型参考

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

Because i is a pointer and you are incrementing the pointer value which will most likely be in steps of 4 (size of NSInteger pointer). Just remove the pointer * reference and you should be good.

NSInteger i = 0;

for ( NSDictionary *teil in gText ) {

In theory you COULD do this the hard way.

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

From:
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
煮茶煮酒煮时光 2024-11-01 16:36:26

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 is not declared as an NSInteger, it's declared as a pointer to an NSInteger.

Since an NSInteger is 4 bytes, when you add 1, the pointer actually increases by the size of 1 NSInteger, or 4 bytes.

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

This confusion is arising because NSInteger is not an object, so you don't need to declare a pointer to it. Change your declaration to this for the expected behaviour:

NSInteger i = 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文