I read in Cocoa and Objective C: Up and Running that -copy
will always return an immutable object and -mutableCopy
will always return a mutable object:
It’s important to know that calling
-copy
on a mutable object returns an immutable version. If you want to copy a mutable object and maintain mutability in the new version, you must call-mutableCopy
on the original. This is useful, though, because if you want to “freeze” a mutable object, you can just call-copy
on it.
So I have something like this:
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
NSLog( @"%@", [req className] ); // NSMutableURLRequest
NSLog( @"%@", [[req copy] className] ); // NSMutableURLRequest
NSLog( @"%@", [[req mutableCopy] className] ); // NSMutableURLRequest
According to this previous answer:
You cannot depend on the result of copy to be mutable! Copying an
NSMutableArray
may return anNSMutableArray
, since that's the original class, but copying any arbitraryNSArray
instance would not.
This seems to be somewhat isolated to NSURLRequest
, since NSArray
acts as intended:
NSArray *arr = [[NSMutableArray alloc] init];
NSLog( @"%@", [arr className] ); // __NSArrayM
NSLog( @"%@", [[arr copy] className] ); // __NSAraryI
NSLog( @"%@", [[array mutableCopy] className] ); // __NSArrayM
So...
- When does
-copy
return an immutable object (as expected) and when does it return a mutable object? - How do I achieve the intended effect of getting a "frozen" copy of a mutable object that refuses to be "frozen"?