Search code examples
iphoneios6

Adding same array multiple times in NSMutableDictionary


I'm trying to add the values in array and storing that array in dictionary. Actually, there are sections in UICollectionView, and each section contains items in it. Each time the array adds values for a section, it adds it into dictionary then clears the array and again next time the array add values for next section and and put to dictionary, but dictionary not holding the value when array objects removed. Below is code i tried.

  NSMutableArray *arrStatus = [seatsDict objectForKey:0];
        if(arrStatus == nil)
        { 
            NSMutableArray *array = [NSMutableArray array];
            array = arrSeatsStatus;
            [seatsDict setObject:array forKey:[NSString stringWithFormat:@"%d",i]];
            i++;
            [arrSeatsStatus removeAllObjects];
        }
        else{       
        NSLog(@"arrStatus:%@", arrStatus);
        [seatsDict setObject:arrSeatsStatus forKey:[NSString stringWithFormat:@"%d",i]];
        i++;
        [arrSeatsStatus removeAllObjects];
        }

In above code array arrStatus is null always, but dictionary is not. Above code not giving desired results. Above code makes dictionary empty when array cleared. Please guide for above.


Solution

  • You are adding a pointer to the array, so the when the the dictionary references the array, it is referencing the original array, which is the one you removed items from. Instead, you will need to create another instance of the array to belong to the dictionary and only the dictionary. the mutableCopy method belongs to NSArray and is used to make an NSMutableArray instance when you have an NSArray (immutable, so you cannot add/remove items). Instead, do it like this:

        NSMutableArray *arrStatus = [seatsDict objectForKey:0];
        if(arrStatus == nil)
        { 
            NSMutableArray *array = [NSMutableArray array];
            array = [arrSeatsStatus copy];
            [seatsDict setObject:array forKey:[NSString stringWithFormat:@"%d",i]];
            i++;
            [arrSeatsStatus removeAllObjects];
        }
        else{       
            NSLog(@"arrStatus:%@", arrStatus);
            [seatsDict setObject:[arrSeatsStatus copy] forKey:[NSString stringWithFormat:@"%d",i]];
            i++;
            [arrSeatsStatus removeAllObjects];
        }
    

    Now the data is copied and can be modified separately. If you are worried about memory, the memory for the copied objects will be deallocated when you remove the objects from the dictionary.