How to return an NSMutableArray from an NSSet

node ninja picture node ninja · Sep 30, 2010 · Viewed 63k times · Source

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?

Answer

dreamlax picture dreamlax · Sep 30, 2010

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];