Reputation: 9130
I usually do option B as it allows me to do some debugging on the dictionary if I need to (as shown in option C). It also looks cleaner in my opinion. This might probably be a non-issue but I'm wondering if options B or C use more memory or if there is even something else to consider when doing this in iOS programming. By the way, I'm using ARC.
Is there an advantage on using option A as opposed to option B or C?
// OPTION A
NSString *someString = [[self grabDictionaryFromDB] objectForKey:@"someField"];
// OPTION B
NSDictionary *dbRow = [self grabDictionaryFromDB]; // dbRow ONLY gets used in the next line
NSString *someString = [dbRow objectForKey:@"someField"];
// OPTION C
NSDictionary *dbRow = [self grabDictionaryFromDB]; // dbRow ONLY gets used in the next two lines
NSLog(@"Row: %@", dbRow);
NSString *someString = [dbRow objectForKey:@"someField"];
Upvotes: 3
Views: 97
Reputation: 3921
I suggest Option B because it is much more easily modified in the future. Let me present two scenarios:
Issue One: You want to perform another operation using that dictionary.
//Option A version
NSString *someString = [[self grabDictionaryFromDB] objectForKey:@"someField"];
NSString *someOtherString = [[self grabDictionaryFromDB] objectForKey:@"someOtherField"];
//Option B version
NSDictionary *myDictionary = [self grabDictionaryFromDB];
NSString *someString = [myDictionary objectForKey:@"someField"];
NSString *someOtherString = [myDictionary objectForKey:@"someOtherField"];
What if [self grabDictionaryFromDB] takes a long time to execute? Suddenly you are executing it twice instead of once, where as you could just be saving the returned dictionary pointer and only execute it once.
Issue Two: What if you suddenly want to access a different dictionary in the future? With the above options, you would only have to change one line of code in Option B, no matter how many times you were accessing the dictionary. In Option B, you just have to change the value of myDictionary. In Option A, you would have to change a bunch of lines of code.
Upvotes: 0
Reputation: 726569
Chances are that options A and B will be optimized into exactly the same output by the compiler, so the only thing that you gain with option B is readability. Option C will likely require an extra store instruction and a pair of [retain]
/ [release]
from the ARC, but you would not notice the impact compared to options A or B.
Upvotes: 2