由编译器优化的变量 [英] Variable optimized away by compiler
问题描述
我开始调试一些试图找出错误的代码。当我从调试器尝试 p tlEntries
时,我得到了
I started debugging some code attempting to find my mistake. When I attempt to p tlEntries
from the debugger I get the
<变量优化远离编译器>
消息在 if
语句时停止。以下是我的代码:
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"]);
}
早期调试让我相信URL确实返回了有效的 NSArray
,但我不明白为什么 tlEntries
正在优化掉。
Earlier debugging gives me confidence the URL is indeed returning a valid NSArray
, but I don't understand why tlEntries
is being "optimized away".
推荐答案
编译器可能注意到您在开始时只使用了两次tlEntries,并且在循环中根本不使用它。如果我没记错的话,循环会创建一个枚举对象,而不是保持对容器对象的引用。所以tlEntries应该对第一行有效,但后来又用完了。
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.
想法:你可以强制编译器通过在函数后面的某个地方使用tlEntries来保留它。类似
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);
更好的想法:您可以将优化设置为-O0。强烈建议您调试代码。如果您使用Debug而不是Release版本,它应该自动设置为-O0,但您可以更改它。
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.
这篇关于由编译器优化的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!