Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,527 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.