代码之家  ›  专栏  ›  技术社区  ›  bpapa

如何安全地管理要从UI中删除的按钮?

  •  0
  • bpapa  · 技术社区  · 15 年前

    我正在制作一个类似iBooks的应用程序。屏幕上有一些东西,每个项目都用一个小缩略图表示。我希望用户能够像点击iBooks中的“编辑”按钮一样删除这些项目-这时会出现一个X,项目就会被删除。我使用委托模式来处理所有这些问题,下面是一些代码:

    // Button is created in CustomView.h class
    UIImage *deleteImage = [UIImage imageNamed:@"delete.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.deleteButton = button;
    [self.deleteButton setImage:deleteImage forState:UIControlStateNormal]; 
    [self.deleteButton addTarget:self action:@selector(deleteIt) forControlEvents:UIControlEventTouchUpInside];
    
    // Here's what's called when the delete button is pushed
    - (IBAction)deleteMap {
    [self.customViewDelegate itemWasDeleted:self];  
    }
    
    // And here's the implementation of that method, in a View Controller
    - (void)itemWasDeleted:self:(CustomView*)customView {
        // delete domain object
        // . . .    
    
        [self.collectionOfCustomViews removeObject:customView];
        [customView removeFromSuperview];
    }
    

    这段代码的问题是我遇到了一个错误的访问异常。通过NSZombie,看起来像这样:

    * -[UIButton\u unhighlight]:发送到解除分配的实例0x5f4a740的消息

    我想发生的事情是,当调用我的目标操作实现时,释放按钮还不安全,就像我在delegate方法中所做的那样。所以我的问题是,有什么更好的方法来做到这一点,以使五月应用程序不崩溃?我想知道最干净的方法。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Ben    15 年前

    如果collectionOfCustomViews是唯一保留customView的对象,则在删除它时将其释放,因此它无法响应removeFromSuperview。