The Man
The Man

Reputation: 1462

For Loop Objective C

Why do I get this as a result to this code?

CODE

ids = 0;
for (NSString *s in golferThreeIconCounter) {
    ids++;
    NSLog(@"%i", ids);
}

RESULT

2012-05-24 16:30:35.194 Dot Golf Scoring[673:f803] 4
2012-05-24 16:30:35.196 Dot Golf Scoring[673:f803] 8
2012-05-24 16:30:35.196 Dot Golf Scoring[673:f803] 12
2012-05-24 16:30:35.197 Dot Golf Scoring[673:f803] 16
2012-05-24 16:30:35.197 Dot Golf Scoring[673:f803] 20
2012-05-24 16:30:35.198 Dot Golf Scoring[673:f803] 24
2012-05-24 16:30:35.199 Dot Golf Scoring[673:f803] 28
2012-05-24 16:30:35.199 Dot Golf Scoring[673:f803] 32
2012-05-24 16:30:35.200 Dot Golf Scoring[673:f803] 36
2012-05-24 16:30:35.200 Dot Golf Scoring[673:f803] 40
2012-05-24 16:30:35.201 Dot Golf Scoring[673:f803] 44
2012-05-24 16:30:35.201 Dot Golf Scoring[673:f803] 48
2012-05-24 16:30:35.202 Dot Golf Scoring[673:f803] 52
2012-05-24 16:30:35.202 Dot Golf Scoring[673:f803] 56
2012-05-24 16:30:35.203 Dot Golf Scoring[673:f803] 60

It makes absolutely no sense to me why ids goes up 4 times instead of just once...

Upvotes: 4

Views: 625

Answers (4)

int ids = 0;
for (NSString *s in golferThreeIconCounter) {
    ids++;
    NSLog(@"%i", ids);
}

Try this. You never declared the type of variable that ids is.

Upvotes: 0

TheHairyGun
TheHairyGun

Reputation: 139

You're printing the "position" count of a pointer which is referenced in an array.

So let me try to clarify that.

A pointer is four bytes. In this case you have an array of pointers. So when you loop over you are printing the int value of the index of the pointer.

Upvotes: 1

Aaron Hayman
Aaron Hayman

Reputation: 8512

You need to increment by using: *ids++ since you've declared it as a reference. Or else you need to declare it as a primitive variable: int ids = 0;

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

When you declare an int, you do not add *: it's not an <id> type. What you have is a pointer to an int; on a 32-bit platform it increments by 4.

int ids = 0;

Upvotes: 14

Related Questions