Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to convert immutable objects to mutable objects (recursive)?

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.

like image 256
martinezdelariva Avatar asked Dec 04 '11 02:12

martinezdelariva


People also ask

What is preferable mutable or immutable classes?

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.

In which situations is it better to use an immutable object?

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.


2 Answers

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];
like image 164
omz Avatar answered Nov 16 '22 02:11

omz


On ARC:

CFBridgingRelease(CFPropertyListCreateDeepCopy(NULL, (__bridge CFPropertyListRef)(immutableArray), kCFPropertyListMutableContainersAndLeaves))

really worked. Thanks brainjam.

like image 36
Hoang Nguyen Huu Avatar answered Nov 16 '22 00:11

Hoang Nguyen Huu