How to append values to an array in Objective-C

别说谁变了你拦得住时间么 提交于 2019-12-20 10:33:30

问题


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:


NSMutableArray *myArray = [NSMutableArray array];

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

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/3698152/how-to-append-values-to-an-array-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!