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.
The mutable version is NSMutableArray , which will allow you to append values. 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. You are leaking memory each time you are allocating an array.
C # in TeluguWe can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array. After inserting the element in the array, the positions or index location is increased but it does not mean the size of the array is increasing.
Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .
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 is NSMutableArray
, which will allow you to append values.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With