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:
NSArray
is not a "mutable" class, meaning it's not designed to be modified after it's created. The mutable version isNSMutableArray
, which will allow you to append values.You can't add primitives like
int
to anNSArray
orNSMutableArray
class; they only hold objects. TheNSNumber
class is designed for this situation.You are leaking memory each time you are allocating an array. Always pair each call to
alloc
with a matching call torelease
orautorelease
.
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);
精彩评论