[英]NSMutableArray EXC_BAD_ACCESS on contained objects
我有一個類,我實現了一個NSMutableArray對象。 現在,當手機進入橫向模式時,NSMutableArray中的所有對象都會從視圖中刪除(但不會從NSMutableArray中刪除),然后當手機回到縱向模式時,我將NSMutableArray中包含的所有對象放入視圖,但是當我嘗試訪問我收到的第一個對象時:EXC_BAD_ACCESS。
這是我的代碼:
- (void) setObjects:(BOOL)hidden andWindow:(UIWindow *)win andTxt:(UITextView *)txt andTarget:(id) target {
//view
key = [win.subviews objectAtIndex:0];
key.hidden = hidden;
buttons = [[NSMutableArray alloc] initWithCapacity:1]; //my array
txtsms = txt;
[...]
}
- (void) addButton:(button *)but {
[key addSubview:[but returnButton]];
[buttons addObject:but];
[but release];
}
- (void) hiddenAllKey {
for (UIView *subview in [key subviews])
if ((subview.tag <= startSpecialPunctuation+1)&&(subview.tag >= spaceButton+1))
[subview removeFromSuperview];
}
- (void) showAllKey {
for(int i = 0; i < [buttons count]; ++i)
[key addSubview:[[buttons objectAtIndex:i] returnButton]]; //this is the problem :|
}
正如Joe Blow所說,這是錯誤的:
- (void) addButton:(button *)but {
[key addSubview:[but returnButton]];
[buttons addObject:but];
[but release];
}
but
不應該以該方法發布。 同樣,這在我心中引起了恐懼:
- (void) setObjects:(BOOL)hidden andWindow:(UIWindow *)win andTxt:(UITextView *)txt andTarget:(id) target {
//view
key = [win.subviews objectAtIndex:0];
key.hidden = hidden;
buttons = [[NSMutableArray alloc] initWithCapacity:1]; //my array
你在哪里發布buttons
? 您的應用只會調用一次該方法嗎? 如果沒有,那么你將會泄漏buttons
。
嘗試build and analyze
您的代碼,修復它識別的任何問題。 如果它仍然崩潰,請發布崩潰的回溯
- (void) hiddenAllKey {
for (UIView *subview in [key subviews])
if ((subview.tag <= startSpecialPunctuation+1)&&(subview.tag >= spaceButton+1))
[subview removeFromSuperview];
}
這也是一個微妙的錯誤。 您正在從使用快速枚舉枚舉的列表中刪除元素。 它可以(應該)容易失敗。
以前,我已經在UIView上編寫了一個類別來刪除所有內容,這可以通過簡單的while循環來實現。 現在,你正在嘗試做什么......你可能會做一個for循環,你自己管理迭代索引,即當你不刪除時,你增加,否則你保持相同。
編輯:建議解決方案:
for (int idx = 0; idx < [[key subviews] count]; )
{
UIView *subview = [[key subviews] objectAtIndex: idx];
if ((subview.tag <= startSpecialPunctuation + 1) && (subview.tag >= spaceButton + 1))
{
[subview removeFromSuperview];
}
else
{
idx++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.