So my problem is basically this, I’m parsing through a mutable array of numbers and strings to try and find variables. I have a private helper method, which is working just fine, and differentiaties between operations (@”+”, @”-“, etc) and variables (@”x”, @”y”, etc). Problem is, the code in my else block below isn’t working. I get inside the else statement just fine with @”x” or @”y”, but the NSSet i’m trying to create isn’t working. I just keep NSLog(ging) “return variables is empty”. Any ideas?
+ (NSSet *)variablesUsedInProgram:(id)program
{
NSMutableArray *stack;
if([program isKindOfClass:[NSArray class]]){
stack = [program mutableCopy];
}
NSSet *returnVariables = nil;
for (int i=0; i<stack.count; i++) {
if ([[stack objectAtIndex:i] isKindOfClass:[NSString class]]) {
if ([self isOperation:[stack objectAtIndex:i]]) {
continue;
} else {
returnVariables = [returnVariables setByAddingObject:[stack objectAtIndex:i]];
if (returnVariables.count == 0) {
NSLog(@"returnVariables is empty");
}
}
}
}
return returnVariables;
}
This is because you’re not initializing returnVariables. Change this line:
to this:
The
-[NSSet setByAddingObject:]is an instance method, meaning it is to be called on an instance of NSSet. It isn’t meant to create a new set from scratch, rather it takes the existing set you call it on and creates a new set which is a copy of that set with an additional object added to it, and returns that new set.Even better, use an NSMutableSet: