How do I convert NSMutableArray to NSArray?

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

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

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

    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

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

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

    you try this code---

    NSMutableArray *myMutableArray = [myArray mutableCopy];
    

    and

    NSArray *myArray = [myMutableArray copy];
    
    0 讨论(0)
提交回复
热议问题