ContentView中的按钮导致MonoTouch运行时崩溃。Monotouch 4.0中的错误?

3

我的应用在MT 3.0版本中运行良好。现在我升级到了新版本后,在一个ContentView中放置的按钮会出现错误。当点击该按钮时,应用程序会崩溃。代码如下:

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPa
    float width = tableView.Bounds.Width - 70;

    var cell = tableView.DequeueReusableCell(kCellIdentifier);
    //if (cell == null)
    //{
    cell = new UITableViewCell(UITableViewCellStyle.Subtitle, kCellIdentifier);
    // }

    var behavior = tvc.behaviors.ElementAt(indexPath.Row);
    cell.TextLabel.Text = behavior.Name;
    cell.TextLabel.Font = UIFont.BoldSystemFontOfSize(22f);
    cell.DetailTextLabel.Text = behavior.Definition;
    var view = UIButton.FromType(UIButtonType.Custom);
    view.Tag = indexPath.Row;
    view.SetImage(UIImage.FromBundle("Images/plus.png"), UIControlState.Normal);
    view.Frame = new RectangleF(width - 50, 10, 50, 50);

    view.TouchUpInside += IncrementBehavior;

    var label = new UILabel(new RectangleF(width - 80, 10, 50, 50));
    label.Text = behavior.CurrentCount.ToString();
    label.BackgroundColor = UIColor.Clear;
    label.Font = UIFont.BoldSystemFontOfSize(24f);
    cell.ContentView.AddSubview(view);
    cell.ContentView.AddSubview(label);
    //cell.BackgroundColor = UIColor.Clear;)

    return cell;
}

void IncrementBehavior(object sender, EventArgs e) {
    var button = (UIButton)sender;
    var tag = button.Tag;
    var behavior = tvc.behaviors[tag];

    var indexpath = NSIndexPath.FromRowSection(tag, 0);
    var newBehavior = Repository.GetBehavior(behavior.Id);
    newBehavior.CurrentCount++;
    Repository.Update(newBehavior);
    tvc.behaviors[tag] = newBehavior;


    tvc.TableView.ReloadRows(new[] { indexpath }, UITableViewRowAnimation.None);

}

我经常遇到以下这些错误:

Name: NSInvalidArgumentException Reason: -[__NSCFSet BridgeSelector]: unrecognized selector sent to instance 0x5c3c570

AND

No constructor found for MonoTouch.UIKit.UIControlEventProxy::.ctor(System.IntPtr)

1
我希望这里有人能回答,因为你肯定不会从Attachmate那里得到任何有用的帮助... - Joel Mueller
1
您能否提供一个自包含的测试用例来展示这个问题? - miguel.de.icaza
当我为按钮分配相同的touchupinside事件处理程序两次时,发生了与我非常相似的事情。 - Radu Simionescu
1个回答

10

不确定这是否是问题所在,但当我升级到4.0时,也遇到了一些随机崩溃。事实证明,4.0 GC更加积极,之前可以得逞的事情现在已经不再合法。

特别是,如果我将事件处理程序分配给按钮,则需要确保在类级别上声明按钮。如果在方法中局部声明按钮,则GC会在其超出作用域时清除引用,然后稍后当事件处理程序尝试触发时,它的引用不再存在。

因此,请尝试将按钮的声明移动到方法外部。


我为每一行都有一个按钮,我应该将它存储在某种集合中吗? - Chris Kooken
那个完美运作了!谢谢...不过这太烦人了。我到处都有这种代码。还有其他方法吗? - Chris Kooken
那是我知道的唯一方式,考虑到机器翻译目前的不完善状态,我怀疑是否会提供更好的解决方法或修复措施。 - Jason
MT 4.0仅仅是在模拟器上运行时更频繁地触发垃圾回收以展示潜在问题。 - miguel.de.icaza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接