views:

81

answers:

2

Hi friends... I m doing this-

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

it returns me 0,1,2,3....count one by one. but i want array with appending these values {0,1,2,3,4,5...}. This is not a big deal but i m unable to find it....sorry...i am new to Iphone.

A: 

You can do like this:

NSMutableArray *temp = [NSMutableArray array]; // Already Autoreleased, 
                                               //   so you don't need to do any more release

for(int i=0;i>count;i++)<br>
{
   [temp addObject:[NSNumber numberWithInt:i]];
   NSLog(@"%i",temp);
}
vodkhang
Make sure to release the `NSMutableArray` afterwards!
Douwe Maan
ah, yeah, I think I need to put the remind in my answer
vodkhang
+3  A: 

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.

Shaggy Frog