문제

I have an NSMutableArray called playersArray in my singleton class which holds for my applications main datasource. Each object of playersArray is a NSDictionary and the content is like :

{
    sgfID = 1;
    sgfPlayer = "<PlayerContact: 0xbf851b0>";
}

PlayerContact is a NSObject subclass containing properties like: NSString * playerName, playerTeam, BOOL PlayerSelected and so on.

In one of my ViewControllers, in viewDidLoad, I want to take a deep copy of playersArray in to a NSMutableArray named duplicatePlayersArray. I do this by

playersArray = [[SGFHelper sharedHelpers] SGFContactsArray];
duplicatePlayersArray = [playersArray mutableCopy];

Now that I have two separate copies, I was under the impression that playersArray and duplicatePlayersArray are two totally different arrays in the memory. However I found that they are NOT!

Even if the debugger shows that they have different memory addresses, their contents have same memory addresses. So when i do this:

[((NSMutableDictionary *)[duplicatePlayersArray objectAtIndex:0]) setObject:@"333" forKey:@"sgfID"];

playersArray's dictionary at index:0 has ALSO "333" as key "sgfID" instead of "1" as it used to before the above line of code ran.

BUT, if I run the below code, only then, the two arrays start to differ

[duplicatePlayersArray replaceObjectAtIndex:0 withObject:tempDict];

Still this doesn't address my concern because the two arrays which I wanted to believe are different are still "connected". A change in one, results in the other array to change its contents.

Can you friends please show me a way to DEEP COPY the array I explained the contents of in a way where all of their contents are kept in different objects.

도움이 되었습니까?

해결책

Use initWithArray:copyItems: to copy each entry in the array

NSMutableArray *duplicatePlayersArray = [[NSMutableArray alloc] initWithArray:playersArray copyItems:YES];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top