BruceLee
DocumentDiscussion

导航

 

原始代码

[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
本博原创文章版权归博客园和本人共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出作者名称和原文连接,否则保留追究法律责任的权利。
posted on 2012-09-25 17:23  Bruce Lee  阅读(2312)  评论(3编辑  收藏  举报