views:

4910

answers:

2

Objective-C: how do I convert NSMutableArray to NSArray?

+21  A: 

An NSMutableArray is a subclass of NSArray so you won't always need to convert but if you want to make sure that the array can't be modified you can create a NSArray either of these ways depending on whether you want it autoreleased or not:

/* Not autoreleased */
NSArray *array = [[NSArray alloc] initWithArray:mutableArray];

/* Autoreleased array */
NSArray *array = [NSArray arrayWithArray:mutableArray];
m5h
+10  A: 
NSArray *array = [[mutableArray copy] autorelease];

Copy makes inmutable copies. This is quite useful because Apple can make various optimizations. For example sending copy to a inmutable array only retains the object and returns self.

Georg
this answer is great, but how can I tell from the docs that `copy` creates a normal NSArray and not an NSMutableArray?
Yar