How to return an NSMutableArray from an NSSet

Objective CCocoa TouchNsmutablearrayNsarrayNsset

Objective C Problem Overview


I'm able to put the contents of an NSSet into an NSMutableArray like this:

NSMutableArray *array = [set allObjects];

The compiler complains though because [set allObjects] returns an NSArray not an NSMutableArray. How should this be fixed?

Objective C Solutions


Solution 1 - Objective C

Since -allObjects returns an array, you can create a mutable version with:

NSMutableArray *array = [NSMutableArray arrayWithArray:[set allObjects]];

Or, alternatively, if you want to handle the object ownership:

NSMutableArray *array = [[set allObjects] mutableCopy];

Solution 2 - Objective C

I resolved crashing by using NSMutableArray's method 'addObjectsFromArray' to assign all NSSet objects to NSMutableArray like:

[mutableArray addObjectsFromArray:[cg_Schedule.schedule_Days allObjects]];

Hope this will helps you.

Solution 3 - Objective C

For an ordered set use:

NSArray *myArray = [[myOrderedSet array] mutableCopy];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnode ninjaView Question on Stackoverflow
Solution 1 - Objective CdreamlaxView Answer on Stackoverflow
Solution 2 - Objective CIrfanView Answer on Stackoverflow
Solution 3 - Objective CDustinView Answer on Stackoverflow