Welcome to the Treehouse Community
Looking to learn something new?
Mia Pivirotto5,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?
Martin WildfeuerCourses Plus Student 11,071 Points
Adding multiple items to an array can be achieved with:
- (void)addObjectsFromArray:(NSArray<ObjectType> *)otherArray;
// 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 Shockley6,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.