Objective-c – Variable optimized away by compiler


I started debugging some code attempting to find my mistake. When I attempt to p tlEntries from the debugger I get the

<variable optimized away by compiler>

message while stopped on the if statement. The following is my code:

NSArray *tlEntries = [[NSArray alloc] initWithArray:[self fetchJSONValueForURL:url]];
for (NSDictionary *info in tlEntries) 
    if ([info objectForKey:@"screen_name"] != nil)
         NSLog(@"Found %@ in the timeline", [info objectForKey:@"screen_name"]);

Earlier debugging gives me confidence the URL is indeed returning a valid NSArray, but I don't understand why tlEntries is being "optimized away".

Best Solution

The compiler probably noticed that you only use tlEntries twice in the beginning, and don't use it at all in the loop. Loops create an enumeration object instead of keeping a reference to the container object, if I remember correctly. So tlEntries should be valid for the first line but then gone for the rest.

Idea: You can force the compiler to keep it by using tlEntries somewhere later in the function. Something like

NSPrint(@"IGNORE THIS LINE %p", tlEntries);

Better idea: You can set the optimization to -O0. This is highly recommended for debugging code. It should be set to -O0 automatically if you use the "Debug" instead of "Release" builds, but you can change that.

Related Question