【问题标题】:iPhone App crashes after switching, possibly due to UIImage imageNamediPhone App切换后崩溃,可能是由于UIImage imageNamed
【发布时间】:2011-05-27 19:55:27
【问题描述】:

我的应用程序在屏幕上随机移动 10 个 UIImageView,一旦 UIImageView 到达角落,它就会更改其图像。问题是:在应用程序之间切换并返回我的应用程序后,应用程序崩溃了。

控制台给了我这个消息:

"App" exited abnormally with signal 10: Bus error

崩溃日志指出:

Exception Type:  EXC_BAD_ACCESS (SIGBUS)

Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000011

Crashed Thread:  0  Dispatch queue: com.apple.main-thread

认为问题是由于我使用的是UIImage imageNamed,这里是代码:

ViewController.h中:

UIImage *red;
UIImage *green;
UIImage *blue;

UIImageView *ballOne;
UIImageView *ballTwo;
UIImageView *ballThree;
UIImageView *ballFour;
// And declare UIImageView for other balls
int clr

ViewController.m中:

- (void)viewDidLoad {
  ...
  red = [UIImage imageNamed: @"redTexture.png"];
  green = [UIImage imageNamed: @"greenTexture.png"];
  blue = [UIImage imageNamed: @"blueTexture.png"];
  ...
}
- (void)moveAll:(NSTimer *)theTimer{
  ...
  // If UIImageView touches a corner, Do this:
  clr = arc4random()%3 + 1;
  switch (clr) {
    case 1:
     [ballOne setImage:red];
     break;
    case 2:
     [ballOne setImage:green];
     break;
    case 3:
     [ballOne setImage:blue];
     break;
    default:
     break;
   }
   // And do this for the rest of 9 "balls" 
}

为什么我的应用会崩溃,我该如何解决?

【问题讨论】:

    标签: iphone memory-management crash imagenamed


    【解决方案1】:

    [UIImage imageNamed:] 返回一个自动释放的 UIImage 实例。这意味着一旦事件循环结束,内存就会被释放。

    您需要通过调用来保留这些实例。

    [[UIImage imageNamed:@"blabl.png"] retain]
    

    或(首选方法)通过将蓝色、红色、绿色成员设置为具有

    的属性
    @property(nonatomic, retain) UIImage* red;
    

    你的代码会是这样的:

    - (void)viewDidLoad {
      ...
      self.red = [UIImage imageNamed: @"redTexture.png"];
      self.green = [UIImage imageNamed: @"greenTexture.png"];
      self.blue = [UIImage imageNamed: @"blueTexture.png"];
      ...
    }
    

    当然不要忘记在你完成后释放它们,否则你会遇到与现在相反的情况:内存泄漏。

    释放红色,调用

    [red release]
    

    在dealloc方法中。

    【讨论】:

    • 我很高兴,然后别忘了将问题标记为“已回答”。 (答案左侧的灰色复选标记)
    • 一件小事:当我在不使用“self”的情况下执行此操作时,没有任何改变,但使用“self”,您的方法有效。你能解释一下为什么会有如此大的不同吗?
    • 只能调用self。如果您引用该属性及其保留机制,否则您只需直接访问该成员,而不会从属性功能中受益。阅读apple doc,我特别推荐内存管理文章,如果吸收好,可以避免数小时的调试。干杯
    【解决方案2】:

    总线错误意味着您正在尝试访问 CPU 物理上无法访问的内存。你可能有一个流浪指针。

    也许试试内存分配调试器?

    【讨论】:

    • 嗨,大卫,感谢您的回复。这是我为 iPhone 开发的第三天。你能建议如何通过查看我的代码来避免这种情况吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多