Monotouch Table View 里面動態增加Table View Cell Switch 觸發Switch事件 程序崩潰


原始代碼

[Export("tableView:cellForRowAtIndexPath:")]
public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
    var cell=new UITableViewCell();
    cell=tableView.DequeueReusableCell("MyCell");
    if (cell != null)
    {
        UISwitch myUISwitch = new UISwitch ();
        myUISwitch.ValueChanged += delegate {
            string aa = myUISwitch.On.ToString();
        };
        cell.Add (myUISwitch);       
    }
    return cell;
}

可以正常出來Table View Cell,Cell里面也有動態增加進來Swith,但一觸發事件,就崩潰。

不動態增加Switch,界面上拖Switch到Cell,也可以正常出來Switch,然后通過

UISwitch mySwitch = (UISwitch)cell.ViewWithTag();也可以獲取到Switch,但一觸發事件也是崩潰。

 

原因:

當你GetCell方法返回后,單元格實例不再具有任何引用。是由於被GC收集了。
然而,您的UITableViewCell的本地部分仍然存在(被自身引用的),所以在界面上看起來沒問題 - 但是當您使用事件處理程序,它會嘗試返回到托管代碼...但Switch實例已經不存在了(它會崩潰)。

有幾種方法來處理。一種方法是保持每個單元格創建的引用,例如:保存單元格到靜態列表<UITableViewCell>。 GC將無法收集他們,這樣的事件處理程序稍后將可以找到對象。

說白了就是用靜態變量保存住被GC回收的內容。

 

解決的代碼:

[Export("tableView:cellForRowAtIndexPath:")]
public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
    var cell=new UITableViewCell();
    cell=tableView.DequeueReusableCell("MyCell");
    if (cell != null)
    {
        UISwitch myUISwitch = new UISwitch ();
        UISwitch myUISwitch2 = (UISwitch)cell.ViewWithTag (1000);

        myUISwitch.ValueChanged += delegate {
            string aa = myUISwitch.On.ToString();
        };
        myUISwitch2.ValueChanged += delegate {
            string dd = myUISwitch2.On.ToString();
        };
        cell.AccessoryView = myUISwitch;
        cell.AccessoryView = myUISwitch2;
        cells.Add (cell);       
    }
    return cell;
}

 

作者:Bruce Lee
出處: http://www.cnblogs.com/BruceLee521
本博原創文章版權歸博客園和本人共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出作者名稱和原文連接,否則保留追究法律責任的權利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM