开发者

How to append values to an array in Objective-C

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 wi开发者_如何学Goth 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.


NSMutableArray *myArray = [NSMutableArray array];

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

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


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜