我將一些代碼轉換爲ARC。代碼在NSMutableArray中搜索一個元素,然後找到,移除並返回該元素。問題是,該元素能夠順利通過「removeObjectAtIndex」立即釋放:removeObjectAtIndex導致「消息發送到解除分配的實例」
- (UIView *)viewWithTag:(int)tag
{
UIView *view = nil;
for (int i = 0; i < [self count]; i++)
{
UIView *aView = [self objectAtIndex:i];
if (aView.tag == tag)
{
view = aView;
NSLog(@"%@",view); // 1 (view is good)
[self removeObjectAtIndex:i];
break;
}
}
NSLog(@"%@",view); // 2 (view has been deallocated)
return view;
}
當我運行它,我得到
*** -[UIView respondsToSelector:]: message sent to deallocated instance 0x87882f0
在第二日誌語句。
Pre-ARC,我在調用removeObjectAtIndex之前小心的保留了對象,然後自動釋放它。我如何告訴ARC做同樣的事情?
什麼'[自removeObjectAtIndex:我];'怎麼辦? – hypercrypt