开发者

Set NSString based on condition

开发者 https://www.devze.com 2023-03-12 17:23 出处:网络
I am struggling with the best way to create a NSString object with alloc/init, and then set its contents based on a conditio开发者_StackOverflown.

I am struggling with the best way to create a NSString object with alloc/init, and then set its contents based on a conditio开发者_StackOverflown.

I try this:

        if (amount==@"current") { 
            NSString * suffix=[[NSString alloc] initWithFormat:@"contents1"];
        } else {
             NSString * suffix=[[NSString alloc] initWithFormat:@"contents2"];
        }

however if I try to use "suffix" anywhere, the compiler doesn't like it; claims it is undeclared.

However, since I want a simple inmutable string, I cannot set it before the "if" and then assign it during the "if" so I'm not sure how to approach this?


Your original code fails because you are declaring the string variable within the branches of the if/else. This declaration is local to its curly-braces and does not exist outside of them. If you move the declaration outside the if statement, you can use the branches of the if to assign to this (shared) variable:

BOOL isCurrent = [amount isEqualToString:@"current"];
if (isCurrent) {
    suffix = @"contents1";
} else {
    suffix = @"contents2";
}

Conditional assignment is a good place to use the ternary operator ?:. P? X : Y is similar to if (P) X; else Y;. Unlike if, which is a statement that relies on assignment and other side effects to affect its environment, ?: is an expression that returns the value of the chosen branch. You can use ?: to do what you want like so:

BOOL isCurrent = [amount isEqualToString:@"current"];
NSString *suffix = isCurrent? @"contents1" : @"contents2";


Try declaring NSString *suffix; before you do the if/else statement:

NSString *suffix;
if ([amount isEqualToString:@"current"]) {
suffix = @"contents1";
} else {
suffix = @"contents2";
}

That should work. (Also, you can't use == for NSStrings).

0

精彩评论

暂无评论...
验证码 换一张
取 消