About a year ago, when I first got into programming, I learned the hard way that variables don’t escape the scope of the condition they’re created in. For example:
-(void)someMethod {
if (x == y) {
NSString *string = [[NSString alloc] initWithString:@"Foo"];
NSLog(string); // outputs "Foo" to console successfully
}
...
NSLog(string); // Doesn't work, we're out of the scope of the "if" statement.
}
My question is, is there any way to dynamically create variables within a conditional statement and be able to access them at other times, kind of like if I declared it in my @interface?
EDIT I guess I didn’t explain it well, I meant if I wanted to use it later in other methods.
You just need to declare (and optionally initialize) the variable outside of the if. So something like:
EDIT
To respond to your clarification, ‘string’ here is a local variable, local to this method. You have other options like instance variables for example. Instance methods like this one (ones that start with ‘-‘) will have access to this instance’s (this object’s) instance variables.
So you could do:
Obviously there’s more to this than you can get in a short answer. You can have global variables. If you’re new to the language, you should read properties as a very useful tool for encapsulating instance variables (useful when you want to get the memory mgmt right). But hopefully that gets you pointed in the right direction at least.