Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Mia Pivirotto
Mia Pivirotto
5,557 Points

How to add multiple items to an array with one line of code?

Is there a way to add multiple menuItems to the itemsOrdered array in one line of code? I know Gabe mentioned trying to figure out how to do it, but I'm not sure of the syntax.

Instead of having to do [group1 addMenuItem:grilledCheese]; [group1 addMenuItem:grilledCheese]; [group1 addMenuItem:grilledCheese]; every time I want to add something to the table check, is there a way to make that a little more efficient for adding multiple items to the same order?

Kyle Johnson
Kyle Johnson
33,528 Points

Can you provide this iOS course you are working on?

Mia Pivirotto
Mia Pivirotto
5,557 Points

I'm doing iOS Development with Objective C Track but specifically in the Object Oriented Objective-C course and specifically either during or after the videos we started learning how to make custom classes. Working on the program called Dale's Diner.

2 Answers

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

There is multiple ways to achieve this, have a look at Apples documentation on NSArray. As you want to change your array items, NSMutableArray. Moreover, always a good resource is Ray Wenderlich.

Adding multiple items to an array can be achieved with:

- (void)addObjectsFromArray:(NSArray<ObjectType> *)otherArray;

Example:

// First, we initialize an empty mutable array
NSMutableArray *cheeseList = [NSMutableArray array];

// Now we can add multiple items in one guy, provided that
// cheddar, edamer and grilled exist
[cheeseList addObjectsFromArray: @[cheddar, edamer, grilled]];

Please note: this is untested, please let me know if you encounter any problems :)

Ben Shockley
Ben Shockley
6,094 Points

One way you might be able to do it, is to create a new array of the items you want to add to the array, and then append the new array to the end of the old array.