4

I have code similar to this

if (count == 0)
{
    [array1 addObject:@"No Items"];
} 
else
{
    int x;
    for (x = 0;x <= count; x++) 
    {
            [array1 addObject:[itemsArray objectAtIndex:x];
            NSLog(@"%@",array1);
    }
}

itemsArray has numbers in it (0-40). My expected result is:

  • 1
  • 2
  • 3
  • ...

However it actually does:

  • 1
  • 1,2
  • 1,2,3
  • 1,2,3,4
  • 1,2,3,4,5
  • ...

Why does this happen? If possible, I'd also like to ask for an example to use fast enumeration for this situation (if it suits for this).

Thanks in advance.

2
  • well it might be because you give the NSLog The full array, NSLog(@"%@",[array1 objectAtIndex:x]); or something like that Commented Oct 21, 2011 at 8:24
  • 1
    It seems like you could be using addObjectsFromArray: instead if looping through itemsArray. Commented Oct 21, 2011 at 12:25

2 Answers 2

21

You are NSLoging the whole array, not the current index of array1. What you are seeing logged is what you've coded - to log what you are expecting, change NSLog(@"%@",array1); to NSLog(@"%@",[array1 objectAtIndex:x]);

To confirm add the following after your assignment loop:

for (NSObject* o in array1)
{
    NSLog(@"%@",o);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cool! It did worked, indeed I didn't know how to use NSLog properly. I thought fast enumeration could be used substitution for for loops, is it only for logging?
3

Use NSLog(@"%@", [array1 objectATIndex:x]);

if (count == 0)
{
    [array1 addObject:@"No Items"];
} 
else
{
    int x;
    for (x = 0;x <= count; x++) 
    {
            [array1 addObject:[itemsArray objectAtIndex:x];
            NSLog(@"%@", [array1 objectATIndex:x]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.