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

标签 iphone ios uibutton target-action

我正在制作一个有点像 iBooks 的应用程序。屏幕上有一些内容,每个项目都由一个小缩略图表示。我希望用户能够删除这些项目,就像您点击 iBooks 中的“编辑”按钮一样 - 出现一个 X,并且该项目被删除。我使用委托(delegate)模式来处理所有这些,所以这里是一些代码:

// 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 _unhighlight]: message sent to deallocated instance 0x5f4a740

我猜发生的情况是,当调用我的目标操作实现时,释放按钮尚不安全,正如我在委托(delegate)方法中所做的那样。所以我的问题是,有什么更好的方法可以做到这一点,这样应用程序就不会崩溃?我想知道最干净的方法。

最佳答案

如果collectionOfCustomViews是唯一保留customView的对象,那么当您删除它时释放它,因此它无法响应removeFromSuperview。

关于iphone - 如何安全地内存管理要从 UI 中删除的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3875825/

相关文章:

iphone - 有什么办法可以增加UITableViewCell中detailTextLabel的宽度?

iphone - iOS中不同tableView中单元格的高度

objective-c - UIButton 立即购买效果

ios - 如何从父 ios 应用程序调用 watchkit 扩展中的方法

ios - 我可以获取纬度和经度,但无法访问 SWIFT 中的 GPS 高度信息

iphone - 如何使用标签访问 UIButton 并更改其图像?

iphone - UIButton 内存管理 - 如何管理它?

ios - UITextField becomeFirstReponder 不工作

iphone - 在 iOS 中调试文件句柄泄漏

ios - 将一个简单的应用程序转换为具有标签栏