我正在制作一个有点像 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/