【问题标题】:Confused About Debugger Inconsistency With [NSBundle mainBundle]对调试器与 [NSBundle mainBundle] 不一致感到困惑
【发布时间】:2010-11-29 20:22:57
【问题描述】:

在过去的几个小时里,Xcode 调试器似乎一直在玩弄我的恶作剧。

我正在使用这段代码——事后看来——一个非常明显的错误,但当时并不明显:

- (UIImage*)loadBundleImage:(NSString*)imageName {   
    NSBundle* bundle = [NSBundle mainBundle];
    NSString* path = [bundle bundlePath];
    path = [path stringByAppendingFormat:@"%@/%@", path, imageName];
    return [UIImage imageWithContentsOfFile:path];
}

我使用调试器单步调试代码,在调用 [NSBundle mainBundle] 之后,它一直说 bundle 为 nil。这导致我四处寻找可能发生这种情况的原因,并尝试解决那个问题。

最终,我发现了真正的错误(即我添加了两次路径),所以我决定做一些实验......显然,bundle 不是 nil,那为什么调试器说它是?单步执行 this 代码时,调试器会在 mainBundle 调用后正确显示 bundle 的值:

- (UIImage*)loadBundleImage:(NSString*)imageName {   
    NSBundle* bundle = [NSBundle mainBundle];
    if (bundle == nil) {
        NSLog(@"Nil bundle");
    }
    NSString* path = [bundle bundlePath];
    path = [path stringByAppendingFormat:@"/%@",imageName];
    return [UIImage imageWithContentsOfFile:path];
}

那么,这里给出了什么?这是调试器的错误吗?我唯一疯狂的猜测是编译器正在将对 mainBundle 和 bundlePath 的连续调用优化为某种原子操作,因此调试器无法“看到”发生了什么......但是当我打破这两个调用时加上 if 块...迫使编译器分别处理它们?!

任何人都可以对此有所了解吗?我有我感觉的那么疯狂吗?请告诉我我错了,我可以重新相信调试器。

谢谢,抱歉,这里的迷你咆哮。

【问题讨论】:

  • 嗨,您对优化可能是正确的。这是一个调试版本,对吧?您为目标的 GCC_OPTIMIZATION_LEVEL 设置了什么?
  • 您应该将您的评论更改为一个答案,这样我就可以为您提供信用。果然,我检查了 Release 而不是 Debug(不知道为什么——可能只是我在胡闹,忘记把东西放回去)。调试器现在能够正确调试问题代码。我肯定是在艰难地学习这款 iPhone 的东西。谢谢!!
  • 要构造路径,应该使用 -stringByAppendingPathComponent: 而不是使用 -stringWithFormat: 手动构造路径。

标签: iphone objective-c xcode debugging


【解决方案1】:

我看到您已经解决了这个问题,但是在最新的 XCode 版本中,当您尝试在发布版本中打印它时,调试器控制台应该显示“变量 X 已被优化掉”。

【讨论】:

  • 我将此标记为已接受的答案,这样我就不会因为不接受答案而受到指责。 (上面jib的评论是实际答案......但不能接受cmets作为答案。)
【解决方案2】:

您应该使用 stringByAppendingPathComponent: 来构建您的路径,而不是在斜线字符上进行标记。我在 UIImage 上有一个标准类别,可以从 Resources 文件夹中获取图像:

+(UIImage*)imageFromResourceFileNamed:(NSString*)name;
{
if(!name) return nil;
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:name];
return [[[UIImage alloc] initWithContentsOfFile:path] autorelease];     

}

像这样使用它:

UIImage *prettyImage = [UIImage imageFromResourceFileNamed:@"flower.png"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2012-07-22
    • 2013-05-13
    • 2020-04-16
    相关资源
    最近更新 更多