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
2009-11-20 08:08:02
+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
2009-11-20 08:20:16
this answer is great, but how can I tell from the docs that `copy` creates a normal NSArray and not an NSMutableArray?
Yar
2010-05-16 23:52:48