41

I'm doing this:

for(int i=0;i>count;i++)
{
    NSArray *temp=[[NSArray alloc]initWIthObjects]i,nil];
    NSLog(@"%i",temp);
}

It returns to me 0,1,2,3....counting one by one, but I want an array with appending these values {0,1,2,3,4,5...}. This is not a big deal, but I'm unable to find it. I am new to iPhone.

1
  • Don't use br tags. Use the "101010" button to format code. Commented Sep 13, 2010 at 6:13

3 Answers 3

81
NSMutableArray *myArray = [NSMutableArray array];

for(int i = 0; i < 10; i++) {
   [myArray addObject:@(i)];
}

NSLog(@"myArray:\n%@", myArray);
Sign up to request clarification or add additional context in comments.

2 Comments

Make sure to release the NSMutableArray afterwards!
It should probably be i < count in the for loop. But you just copied it from @user440485's original.
15

This code is not doing what you want it to do for several reasons:

  1. NSArray is not a "mutable" class, meaning it's not designed to be modified after it's created. The mutable version is NSMutableArray, which will allow you to append values.

  2. You can't add primitives like int to an NSArray or NSMutableArray class; they only hold objects. The NSNumber class is designed for this situation.

  3. You are leaking memory each time you are allocating an array. Always pair each call to alloc with a matching call to release or autorelease.

The code you want is something like this:

NSMutableArray* array = [[NSMutableArray alloc] init];
for (int i = 0; i < count; i++)
{
    NSNumber* number = [NSNumber numberWithInt:i]; // <-- autoreleased, so you don't need to release it yourself
    [array addObject:number];
    NSLog(@"%i", i);
}
...
[array release]; // Don't forget to release the object after you're done with it

My advice to you is to read the Cocoa Fundamentals Guide to understand some of the basics.

1 Comment

Under ARC the compiler automatically inserts the necessary retain and release calls. So just do array = nil;
1

A shorter way you could do is:

NSMutableArray *myArray = [NSMutableArray array];

for(int i = 0; i < 10; i++) {

   [myArray addObject:@(i)];
}

NSLog(@"myArray:\n%@", myArray);

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.