BuySellAds.com

Our DNA is written in Objective-C
Jump

Adding Numbers to an Array

reembertoparada asks:

I have a loop from 1 to 30 and I want to create an NSArray with those values inside. Can you give me an idea on how to do this.

That’s an easy after-dinner exercise. First you need to take an NSMutableArray instead of an NSArray because regular objects without “mutable” in their class name cannot be changed. This is especially vital to know for arrays and dictionaries.

Secondly you did not specify which data type you want the number to be added in. Since you can only add Cocoa objects to Cocoa arrays only two types are possible: NSNumber or NSString. In this example I’ll show you both.

	NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:30]; // needs to be mutable
 
	for (int x=0; x<30;x++)
	{
		// add as NSString
		[myArray addObject:[NSString stringWithFormat:@"%d", x]];
 
		// or add as NSNumber
		[myArray addObject:[NSNumber numberWithInt:x]];
	}
 
	// easy way to look what is now in the array
	NSLog([myArray description]);

For both cases we are using a factory method that returns an object of its type, marked as autoreleased. addObject retains it, so they will stick around while the array is alive. You could have used alloc-init-release as well, in this example the array is autoreleased.

You don’t need to use the constructor method with the arrayWithCapacity, but if you know the initial capacity it is good to specify it. NSMutableArray will still grow and shrink, but your code just feels more thoughtful this way.

PS: The for loop in the example does not go from 1 through 30, but actually it iterates from 0 to 29, note the “< 30″. Add +1 to x to get values from one to thirty.


Categories: Q&A

%d bloggers like this: