NSInteger counts times 4?
Asked Answered
M

2

5

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);
Martres answered 22/3, 2011 at 22:45 Comment(0)
P
11

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
Polyphonic answered 22/3, 2011 at 22:51 Comment(3)
Ah, so NSInteger isn't a regular Object like all the other NSS..., it's a primitive type?Martres
Yes, actually it's interesting because it's a typedef to either long or int. I'll include the snip from the documentation.Polyphonic
Well,seems like making 64 bit more intuitive...fine for me, thanks :)Martres
C
1

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;
Chrischrism answered 22/3, 2011 at 22:49 Comment(1)
"i is not declared as an NSInteger, it's declared as an NSInteger." uhhh... wat?Obannon

© 2022 - 2024 — McMap. All rights reserved.