I wrote this following Objective-C code as part of Stanford’s iTunes U course on iOS programming. Are there any ways to simplify this code? The requirement is that this method return nil if the set is empty, not an empty NSSet. It’s also required to take an (id), not an NSArray, and that the method doesn’t crash no matter what values are passed into it.
+ (NSSet *)variablesUsedInProgram:(id)program {
NSMutableArray *stack;
id variables;
NSMutableSet *setOfVariables;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
int i = stack.count;
while (i--) {
if ([[stack objectAtIndex:i] isKindOfClass:[NSString class]]) {
if ([self isOperation:[stack objectAtIndex:i]]) {
[setOfVariables addObject:[stack objectAtIndex:i]];
}
}
}
}
if (setOfVariables.count > 0) {
variables = setOfVariables;
}
return variables;
}
variablesandsetOfVariablesare never initialised. In the case wheresetOfVariables(assuming it was initialised) has a count of 0, the method will return an uninitialised value. I’m not sure why you need a mutable copy ofprogramsince you never modify the array. I’m not sure why you need a copy of it at all actually, and you don’t actually release it either (which is OK if you are using ARC or GC, but not if you are using MRC). This is how I would refactor it, the observable behaviour shouldn’t be different to your method.