I found a few questions like this but I couldn't find this particular question. I have a number of strings that are initialized as
NSString *string = [[NSString alloc] init];
which are then assigned a value depending on the results of an if/else block:
if ([anotherThing isEqualToString:@"boogers"]) {
string = [NSString stringWithFormat:@"some characters"];
} else {
string = [NSString stringWithFormat:@"some _other_ characters"];
}
and then string
is used later in the method.
How can I accomplish this without leaving a dead store at the alloc/init stage? If I alloc inside the if (or the else), the string is gone by the time I need it several lines down.
You don't have to initialize the string on that first line -- you just need to declare it:
NSString *string = nil;
if ([anotherThing isEqualToString:@"boogers"]) {
string = @"some characters";
} else {
string = @"some _other_ characters";
}