martinezdelariva martinezdelariva - 1 year ago 101
Objective-C Question

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.

omz omz
Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download