How do I convert NSMutableArray to NSArray?

前端 未结 9 823
清酒与你
清酒与你 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

提交回复
热议问题