Domanda

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.

È stato utile?

Soluzione

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";
}

Altri suggerimenti

The [NSString stringWithFormat:] will initialize a new NSString object for you, basically what you are doing is declaring a new object each time, just set the pointers for your strings as NSSTring *someString, *someOtherString, *allTheStringsYouNeed; and then use any class method to initialize it even @"Characters"; will work correctly as the compiler do it at runtime for you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top