How do I convert NSMutableArray to NSArray?

前端 未结 9 764
清酒与你
清酒与你 2020-12-04 04:38

How do I convert NSMutableArray to NSArray in objective-c?

相关标签:
9条回答
  • 2020-12-04 05:08

    In objective-c :

    NSArray *myArray = [myMutableArray copy];
    

    In swift :

     var arr = myMutableArray as NSArray
    
    0 讨论(0)
  • 2020-12-04 05:12

    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]
    
    0 讨论(0)
  • 2020-12-04 05:13

    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.

    0 讨论(0)
  • 2020-12-04 05:14

    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
    
    0 讨论(0)
  • 2020-12-04 05:19
    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.

    0 讨论(0)
  • 2020-12-04 05:23

    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
    
    0 讨论(0)
提交回复
热议问题