In the Beginning iPhone 4 book, the author has this code to create a category for creating a deep copy of an NSDictionary that has an NSArray of names for each letter of the alphabet to show an example of an indexed table with a search bar.
#import "NSDictionary-MutableDeepCopy.h"
@implementation NSDictionary (MutableDeepCopy)
- (NSMutableDictionary *) mutableDeepCopy {
NSMutableDictionary *returnDict = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
NSArray *keys = [self allKeys];
for (id key in keys) {
id oneValue = [self valueForKey:key];
id oneCopy = nil;
if ([oneValue respondsToSelector:@selector(mutableDeepCopy)]) oneCopy = [oneValue mutableDeepCopy];
else if ([oneValue respondsToSelector:@selector(mutableCopy)]) oneCopy = [oneValue mutableCopy];
if (oneCopy == nil)
oneCopy = [oneValue copy];
[returnDict setValue:oneCopy forKey:key];
[oneCopy release];
}
return returnDict;
}
@end
Can someone explain the for loop logic? I’m not sure what he’s trying to do in seeing which value responds to which selector, and why it would be added to the dictionary. Thanks.
So, the for loop simply iterates through all the keys in the dictionary. Beforehand, we create a new dictionary called
returnDict– this will be what we return.For each key in the dictionary we want to copy, we…
Get the object stored for that key (
[self valueForKey:key]), and save it into a variable calledoneValue.If
oneValueimplements ourmutableDeepCopymethod (ie, it’s anNSDictionary) go call it, and assign the return value into a variable calledoneCopy.Else, we see if
oneCopyimplements themutableCopymethod. If it does, we put the output into theoneCopyvariable.At this point, we check to see if following steps (2) and (3) the
oneCopyvariable has had anything assigned to it (if (oneCopy == nil)). If it doesn’t (ie, it’s equal tonil) we can assume the object doesn’t implement eithermutableDeepCopyormutableCopy, so we instead call a plain oldcopyand assign its value tooneCopy.Add
oneCopyinto ourreturnDictdictionary using the original key.That’s the for loop – at the end of it all, we go and return the copied dictionary.