0

I am trying to inset key value pair with dynamic array values with following code. It replace the array content of all values with last stored array object. Please suggest how to store copy of array instead of reference. Sample code:

  for (i = i - 1; i >= 0; i--) {
        [dict setObject:urlArray forKey:rootDate];
        [urlArray removeAllObjects];
        [urlArray addObject:[[history objectAtIndex:i] objectAtIndex:0]];
    }

Also tried for setValue method returning same result.

{
"18/03/15" =     (
    "http://www.yahoo.com"
);
"24/03/15" =     (
    "http://www.google.com",
    "http://www.youtube.com"
);

} Actual Output received:

{
"18/03/15" =     (
    "http://www.google.com",
    "http://www.youtube.com"
);
"24/03/15" =     (
    "http://www.google.com",
    "http://www.youtube.com"
);

}

Code cracker
  • 3,105
  • 6
  • 37
  • 67
Gobi M
  • 3,243
  • 5
  • 32
  • 47
  • possible duplicate of [Deep copying an NSArray](http://stackoverflow.com/questions/647260/deep-copying-an-nsarray) – Aaron Brager Mar 24 '15 at 05:17
  • Your code always uses the same key, so your dictionary will contain it only once. And your loop is weird. You assume that the array is set before the first iteration, and after the last iteration it contains data that hasn't been added to the dictionary. – gnasher729 Mar 24 '15 at 08:12

2 Answers2

2

Just create copy/mutableCopy as per your needs of the urlArray

for (i = i - 1; i >= 0; i--) {
        [dict setObject:[urlArray copy] forKey:rootDate];
        [urlArray removeAllObjects];
        [urlArray addObject:[[history objectAtIndex:i] objectAtIndex:0]];
    }
Sanjay Mohnani
  • 5,947
  • 30
  • 46
1
for (i = i - 1; i >= 0; i--) {
        [dict setObject:[urlArray mutableCopy] forKey:rootDate];
        [urlArray removeAllObjects];
        [urlArray addObject:[[history objectAtIndex:i] objectAtIndex:0]];
    }

You can also use [urlArray copy] if you don't want your array to be mutable.

Burhanuddin Sunelwala
  • 5,318
  • 3
  • 25
  • 51