Original code
[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;
}
The table view cell can be normally displayed, and swith is also dynamically added in the cell. However, once an event is triggered, it will crash.
If you do not dynamically Add a switch, you can drag the switch to the cell on the interface.
Uiswitch myswitch = (uiswitch) cell. viewwithtag (); you can also obtain the switch, but a trigger event also crashes.
Cause:
When the getcell method returns, the cell instance no longer has any reference. It is collected by GC.
However, the local part of your uitableviewcell still exists (referenced by itself), so it looks okay on the Interface-but when you use the event handler, it will try to return to the managed code... but the switch instance does not exist anymore (it will crash ).
There are several methods for processing. One way is to keep the reference created by each cell. For example, save the cell to the static list <uitableviewcell>. GC will not be able to collect them, and such an event handler will be able to find objects later.
To put it bluntly, static variables are used to save the content recycled by GC.
Solution code:
[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;
}
By Bruce Lee
Source: http://www.cnblogs.com/BruceLee521
This blog Original article is copyrighted by the blog and I share it with you. You are welcome to reprint it. However, you must keep this statement without the author's consent and provide the author name and original article connection clearly on the article page, otherwise, you are entitled to pursue legal liability.