Pergunta

I forgot to initialize a local variable, and I got no warning when I used it. Since I'm using ARC, the variable was initialized to nil, so no harm was done, but I still want a warning when I used an uninitialized value. If I disable ARC, I get the warning I expect.

NSString *foo;
NSString *baz;
if (bar) {
    foo = @"fizz";
} else {
    foo = @"buzz";
}
NSLog(@"foo: %@", foo);  // foo: (fizz|buzz)
NSLog(@"baz: %@", baz);  // baz: (null)

Without ARC:

/blah/blah/blah/Blah.m:14:18: note: initialize the variable 'foo' to silence this warning
NSString *foo;
             ^

--EDIT--

I've figured out how to make uninitialized values impossible using local blocks. This obviates the need for the warning.

Foi útil?

Solução

With ARC, pointers to Objective C objects are automatically initialized to nil, so there is no "uninitialized value" which the compiler can warn about.

Outras dicas

Clang has an option -Wuninitialized that looks like it should do what you want, but as pointed out in another answer, variables are guaranteed to be initialized to 0/nil under ARC.

Martin R is correct:

With ARC, pointers to Objective C objects are automatically initialized to nil, so there is no "uninitialized value" which the compiler can warn about.

However, I've avoided this problem altogether by using local blocks to initialize variables. The block guarantees that all paths end in a return, which means that my variable is guaranteed to be initialized.

The example would be written thusly:

NSString *foo = ^{
    if (bar) {
        return @"fizz";
    } else {
        return @"buzz";
    }
}();
NSLog(@"foo: %@", foo);  // foo: (fizz|buzz)

The block is stack-allocated, so it doesn't incur any overhead beyond a normal function call.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top