How do I convert NSMutableArray to NSArray in objective-c?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
Copy
makes immutable copies. This is quite useful because Apple can make various optimizations. For example sendingcopy
to a immutable array only retains the object and returnsself
.If you don't use garbage collection or ARC remember that
-copy
retains the object.An
NSMutableArray
is a subclass ofNSArray
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 aNSArray
either of these ways depending on whether you want it autoreleased or not: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.
I like both of the 2 main solutions:
Or
The primary difference I see in them is how they behave when mutableArray is nil:
In objective-c :
In swift :
Objective-C
Below is way to convert NSMutableArray to NSArray:
Swift
In Swift 3.0 there is new data type Array. Declare Array using
let
keyword then it would become NSArray And if declare usingvar
keyword then it's become NSMutableArray.Sample code:
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.
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:
The above practice is discussed in more detail here:
Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray