How to add objects to an NSArray using for loop?
72,224
Solution 1
NSArray is immutable. Use the mutable version, NSMutableArray.
Solution 2
NSMutableArray * customTickLocations = [NSMutableArray new];
for (int idx = 0; idx < 12; ++idx) {
[customTickLocations addObject:[NSDecimalNumber numberWithInt:idx]];
}
...
Solution 3
you cannot add Objects at run time to NSArray.For adding or removing objects at Run time you have to use NSMutableArray.
NSMutableArray *mutableArray=[[NSMutableArray alloc] init];
for (int i=0; i<10; i++) {
[mutableArray addObject:[NSDecimalNumber numberWithInt:i]];
}
Solution 4
NSMutableArray *customTickLocations = [NSMutableArray array];
for (int i=0; i<totalImagesOnXaxis; i++)
{
[customTickLocations addObject:[NSDecimalNumber numberWithInt:i]];
}
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 Class Reference
Solution 5
NSMutableArray *customTickLocations = [[NSMutableArray alloc] init];
for(int i = 0; i<WhateverNoYouWant;i++)
{
NSDecimalNumber * x = [NSDecimalNumber numberWithInt:i]
[customTickLocations addObject:x]
}
Related videos on Youtube
Author by
Madan Mohan
Updated on February 08, 2020Comments
-
Madan Mohan over 4 years
I want to add the
[NSDecimalNumber numberWithInt:i]
to an array using for loop.It is hardcoded :
NSArray *customTickLocations = [NSArray arrayWithObjects: [NSDecimalNumber numberWithInt:1],[NSDecimalNumber numberWithInt:2],[NSDecimalNumber numberWithInt:3],[NSDecimalNumber numberWithInt:4],[NSDecimalNumber numberWithInt:5],[NSDecimalNumber numberWithInt:6],[NSDecimalNumber numberWithInt:7],[NSDecimalNumber numberWithInt:8],[NSDecimalNumber numberWithInt:9],[NSDecimalNumber numberWithInt:10],[NSDecimalNumber numberWithInt:11],[NSDecimalNumber numberWithInt:12],nil];
I want like this, but I can add only one object here....
for (int i=0; i<totalImagesOnXaxis; i++) { customTickLocations = [NSArray arrayWithObject:[NSDecimalNumber numberWithInt:i]]; }
Please help me out of this, Thanks in Advance, Madan
-
raymi over 12 yearsWhy do you need the array anyway? Looks like the value in the array at index
i
is alwaysi
.
-