Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add objects to an NSArray using for loop?

Tags:

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

like image 364
Madan Mohan Avatar asked Oct 21 '11 07:10

Madan Mohan


People also ask

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

How do you declare NSArray in Objective C?

In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil.


2 Answers

NSArray is immutable. Use the mutable version, NSMutableArray.

like image 131
EmptyStack Avatar answered Sep 17 '22 19:09

EmptyStack


NSMutableArray * customTickLocations = [NSMutableArray new]; for (int idx = 0; idx < 12; ++idx) {     [customTickLocations addObject:[NSDecimalNumber numberWithInt:idx]]; }  ... 
like image 28
justin Avatar answered Sep 17 '22 19:09

justin