In the following code I want to traverse an NSMutableArray (self.codes) which contains NSMutableDictionary objects. If the value for the “selected” key is equal to “1” then I want to copy the NSMutableDictionary “code” object and add it to the selectedCodes array.
1 -(NSMutableArray *)getSelecedCodes{
2
3 NSMutableArray *selectedCodes=[[NSMutableArray alloc]init];
4
5 for (NSMutableDictionary *code in self.codes) {
6 if([code valueForKey:@"selected"]==@"1"){
7 [selectedCodes addObject:[code copy]];
8 }
9 }
10
11 return selectedCodes;
12
13 }
When I analyze the code in XCode I get a warning of the potential memory leaks. Any thoughts on what I am doing wrong?
-[NSMutableArray addObject:]retains its argument.copyreturns a retained value as well. So you’re retaining the copied dictionary twice.You probably want to do this:
However, depending on your specific needs, there are a couple caveats:
Are you sure you want to copy the dictionary? You can just add it to the array:
[selectedCodes addObject:code];Note that both
selectedCodesandself.codeswill contain pointers to the same dictionary, so changes in one copy will be reflected in the other as well.You might want to create a mutable copy of the dictionary.
copyreturns an immutable object:[selectedCodes addObject:[[code mutableCopy] autorelease]];