Objective-C “if” statements not retaining

后端 未结 3 1436
死守一世寂寞
死守一世寂寞 2021-01-14 17:20

I know the title of this question is a bit confusing, but here it goes anyway:

I\'m creating an NSString after an if statement but it just doesn\'t seem

相关标签:
3条回答
  • 2021-01-14 17:56

    Use:

    NSString* pwd = nil;
    if ([[password stringValue] isEqualToString:@""]) {
        pwd = [[NSString alloc]initWithString:@"password"];
    } else {
        pwd = [[NSString alloc]initWithFormat:@"%@", [password stringValue]];
    }
    

    The problem is that each block introduces a scope. A variable exists only in the scope in which it is defined (a variable exists from the point of declaration to the end of the scope it is declared). Although the memory pointed to by "pwd" will outlast the if...else block, the pointer named pwd will cease to exist after the if...else block in which it is declared. Declaring the pointer before the block moves pwd up one scope.

    0 讨论(0)
  • 2021-01-14 18:08

    It's not a problem of retaining, but one of scope of your declarations: a declaration within braces has a lexical scope that terminates at the closing brace -- that declaration's just not visible outside of the block! So just move your declaration before the block and have only the initialization within the block, i.e.:

    NSString *pwd;
    if ([[password stringValue] isEqualToString:@""]) {
        pwd = [[NSString alloc]initWithString:@"password"];
    }
    else {
        pwd = [[NSString alloc]initWithFormat:@"%@", [password stringValue]];
    }
    
    0 讨论(0)
  • 2021-01-14 18:11

    You have declared pwd as a local variable inside the bodies of the if. The variable you refer to later is probably declared outside, and is never set by either assignment. Simply remove NSString * from the assignments.

    0 讨论(0)
提交回复
热议问题