0

I want to add string objects to an array inside for loop. Below is my code;

for (int i=0;i<[retrievedArray count];i++)
{
    NSString *temp = [[retrievedArray objectAtIndex:i] OfficialName];
    [detailPgArray addObject:temp];
}

I have 10 objects inside retrievedArray (not as direct strings, but as OfficialName)

But for some reason, at the end of the for loop, detailPgArray has 0 objects. Please help.

4
  • You can format code by highlighting it and then pressing the "{}" button. Commented Jan 26, 2011 at 18:32
  • Is detailPgArray nil? The code looks fine but if detailPgArray is nil it will always return a count of 0 Commented Jan 26, 2011 at 18:32
  • I just declare detailPgArray in the .h file and am trying to set it inside this for loop. I have not set it to nilanywhere else. Commented Jan 26, 2011 at 18:34
  • OfficialName should be officialName if you want to follow Objective-C naming conventions. Commented Jan 26, 2011 at 19:17

4 Answers 4

3

detailPgArray is more than likely nil. You need to allocate somewhere. If it is an instance variable try the following.

[detailPgArray release];
detailPgArray = [[NSMutableArray alloc] initWithCapacity:[retrievedArray count]];

for (int i=0;i<[retrievedArray count];i++)
{
    NSString *temp = [[retrievedArray objectAtIndex:i] OfficialName];
    [detailPgArray addObject:temp];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you all for this wonderful basic learning...YOU ALL ROCK..UNFORTUNATELY I COULD NOT ACCEPT ALL YOUR ANSWERS !
1

I'd guess that you neglected to allocate and initialize detailPgArray. If it's nil, then your -addObject: calls will go merrily into the void and any later calls to -count will return nil or 0.

Comments

0

Most likely, detailPgArray is nil. You need to create an array to go in the variable.

Comments

0

In Objective-C you can send a message to nil and the application won't crash -- and that is what's happening in your code with that addObject call. You have to alloc and init the array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.