Specifically, this problem has come to me when I make a request with AFNeworking with JSONkit and receive a (id)JSON with several arrays and dictionaries nested.
If I don't want to modify the data, I don't have any problem:
self.myNSArray = [JSON objectForKey:@"result"];
But if I want to modify the data I must to store it in a mutable variable:
self.myNSMutableArray = [[JSON objectForKey:@"result"] mutableCopy];
The last one doesn't convert nested arrays or dictionaries to mutable data; it works only for first level.
The only way that I have found is on this link recursive mutable objects; but I don't know if there is a best way to resolve this kind of problem.
Thanks in advance.
It's mutable so you can't return it directly from a method. This means you end up doing all sorts of defensive copying. That increases object proliferation. The other major benefit is that immutable objects do not have synchronization issues, by definition.
Immutable objects can be useful in multi-threaded applications. Multiple threads can act on data represented by immutable objects without concern of the data being changed by other threads. Immutable objects are therefore considered more thread-safe than mutable objects.
You could use the CoreFoundation function CFPropertyListCreateDeepCopy
with the mutability option kCFPropertyListMutableContainersAndLeaves
:
NSArray *immutableArray = [JSON objectForKey:@"result"];
self.myMutableArray = [(NSMutableArray *)CFPropertyListCreateDeepCopy(NULL, immutableArray, kCFPropertyListMutableContainersAndLeaves) autorelease];
On ARC:
CFBridgingRelease(CFPropertyListCreateDeepCopy(NULL, (__bridge CFPropertyListRef)(immutableArray), kCFPropertyListMutableContainersAndLeaves))
really worked. Thanks brainjam.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With