[objective-c] How do I convert NSMutableArray to NSArray?

How do I convert NSMutableArray to NSArray in ?

This question is related to objective-c cocoa-touch cocoa nsmutablearray nsarray

The answer is


you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it so here is the swift 3 code

let array: [String] = nsMutableArrayObject.copy() as! [String]

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.

- (NSArray *)arrayOfStrings {
    NSMutableArray *mutableArray = [NSMutableArray array];
    mutableArray[0] = @"foo";
    mutableArray[1] = @"bar";

    return mutableArray;
}

If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy].

Apple concurs:

To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.

The above practice is discussed in more detail here:

Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray


I like both of the 2 main solutions:

NSArray *array = [NSArray arrayWithArray:mutableArray];

Or

NSArray *array = [mutableArray copy];

The primary difference I see in them is how they behave when mutableArray is nil:

NSMutableArray *mutableArray = nil;
NSArray *array = [NSArray arrayWithArray:mutableArray];
// array == @[] (empty array)

NSMutableArray *mutableArray = nil;
NSArray *array = [mutableArray copy];
// array == nil

NSArray *array = [mutableArray copy];

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

If you don't use garbage collection or ARC remember that -copy retains the object.


In objective-c :

NSArray *myArray = [myMutableArray copy];

In swift :

 var arr = myMutableArray as NSArray

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

EDIT: The solution provided by Georg Schölly is a better way of doing it and a lot cleaner, especially now that we have ARC and don't even have to call autorelease.


NSArray *array = mutableArray;

This [mutableArray copy] antipattern is all over sample code. Stop doing so for throwaway mutable arrays that are transient and get deallocated at the end of the current scope.

There is no way the runtime could optimize out the wasteful copying of a mutable array that is just about to go out of scope, decrefed to 0 and deallocated for good.


Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to cocoa

How to update a single pod without touching other dependencies How to initialise a string from NSData in Swift Input from the keyboard in command line application Get current NSDate in timestamp format Xcode build failure "Undefined symbols for architecture x86_64" Cocoa Autolayout: content hugging vs content compression resistance priority setValue:forUndefinedKey: this class is not key value coding-compliant for the key iOS - Build fails with CocoaPods cannot find header files Get Current date & time with [NSDate date] Remove all whitespaces from NSString

Examples related to nsmutablearray

'Invalid update: invalid number of rows in section 0 How do I convert NSMutableArray to NSArray? The best way to remove duplicate values from NSMutableArray in Objective-C? How do I sort an NSMutableArray with custom objects in it?

Examples related to nsarray

Initialize Array of Objects using NSArray How to convert NSNumber to NSString NSDictionary to NSArray? Convert NSArray to NSString in Objective-C How do I convert NSMutableArray to NSArray? NSArray + remove item from array How do I iterate over an NSArray? Using NSPredicate to filter an NSArray based on NSDictionary keys How can I reverse a NSArray in Objective-C? filtering NSArray into a new NSArray in Objective-C