【问题标题】:Resolve "'NSUnknownKeyException', reason:This class is not key value coding-compliant for the key X” exception解决“'NSUnknownKeyException', reason:This class is not key value coding-compliant for key X”异常
【发布时间】:2016-05-29 04:16:09
【问题描述】:

我遇到了与此提交中确定的完全相同的问题: MvvmCross/Xamarin "This class is not key value coding-compliant for the key"

问题源于尝试在 IOS CollectionView 中使用 MVVMCross 数据绑定

那篇文章已关闭并标记为重复,但我不这么认为。它作为解决方案链接到的文章提供了将 XCode 用作开发环境时的解决方法。我的场景和上面链接的问题中描述的场景是在 Windows 上使用 Visual Studio 和 Xamarin 进行构建。使用 Visual Studio,XIB 编辑器和连接插座的方式有所不同。

我这几天一直在尝试解决这个问题,但没有解决任何问题。我希望在 Windows Visual Studio 中看到这一点的人有一个可以分享的解决方案。

(抱歉,我是新手,所以无法在原帖中发表评论)。

错误的堆栈跟踪如下

Foundation.MonoTouchException: Objective-C exception thrown.  
Name: NSUnknownKeyException Reason: [<NSObject 0x7c4eb9a0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key view.

Native stack trace:

0   CoreFoundation                      0x00928494 __exceptionPreprocess + 180
1   libobjc.A.dylib                     0x08fa3e02 objc_exception_throw + 50
2   CoreFoundation                      0x009280b1 -[NSException raise] + 17
3   Foundation                          0x014477f8 -[NSObject(NSKeyValueCoding) setValue:forUndefinedKey:] + 282
4   Foundation                          0x013a1e6a _NSSetUsingKeyValueSetter + 115
5   Foundation                          0x013a1def -[NSObject(NSKeyValueCoding) setValue:forKey:] + 295
6   Foundation                          0x013d654b -[NSObject(NSKeyValueCoding) setValue:forKeyPath:] + 384
7   UIKit                               0x03bc8a62 -[UIRuntimeOutletConnection connect] + 132
8   libobjc.A.dylib                     0x08fb800c -[NSObject performSelector:] + 62
9   CoreFoundation                      0x00851131 -[NSArray makeObjectsPerformSelector:] + 273
10  UIKit                               0x03bc70fc -[UINib instantiateWithOwner:options:] + 2102
11  UIKit                               0x041205ec -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 750
12  UIKit                               0x04120f35 -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 194
13  ???                                 0x1b909f9c 0x0 + 462462876
14  ???                                 0x1be1b820 0x0 + 467777568
15  ???                                 0x1be1b633 0x0 + 467777075
16  ???                                 0x1be1adf6 0x0 + 467774966
17  ???                                 0x1be1b08d 0x0 + 467775629
18  CompanionForSpotifyiOS              0x001bb2a1 mono_jit_runtime_invoke + 705
19  CompanionForSpotifyiOS              0x00276fef mono_runtime_invoke + 127
20  CompanionForSpotifyiOS              0x0034bb77 xamarin_trampoline + 5559
21  UIKit                               0x0410d5ee -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:] + 448
22  UIKit                               0x0410d2ff -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 65
23  UIKit                               0x04111761 -[UICollectionView _updateVisibleCellsNow:] + 6023
24  UIKit                               0x041167df -[UICollectionView layoutSubviews] + 254
25  UIKit                               0x038543d4 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 810
26  libobjc.A.dylib                     0x08fb8059 -[NSObject performSelector:withObject:] + 70
27  QuartzCore                          0x0b5d8096 -[CALayer layoutSublayers] + 144
28  QuartzCore                          0x0b5cb8b6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 388
29  QuartzCore                          0x0b5cb71a _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
30  QuartzCore                          0x0b5bdee7 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 317
31  QuartzCore                          0x0b5f2847 _ZN2CA11Transaction6commitEv + 561
32  QuartzCore                          0x0b5f3108 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
33  CoreFoundation                      0x0083a75e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
34  CoreFoundation                      0x0083a6be __CFRunLoopDoObservers + 398

ViewModel 代码在这里

public partial class AlbumCell : MvxCollectionViewCell
{
    public static readonly UINib Nib = UINib.FromName("AlbumCell", NSBundle.MainBundle);
    public static readonly NSString Key = new NSString("AlbumCell");

    public AlbumCell(IntPtr handle) : base(string.Empty, handle)
    {
        this.DelayBind(() =>
        {
            var set = this.CreateBindingSet<AlbumCell, Album>();
            set.Bind(artistNameLabel).To(album => album.ArtistName);
            set.Apply();
        });
    }

    public static AlbumCell Create()
    {
        return (AlbumCell)Nib.Instantiate(null, null)[0];
    }
}

这是生成的具有出口的视图模型组件 [注册(“专辑单元”)] 部分类 AlbumCell { [出口] [GeneratedCode ("iOS Designer", "1.0")] UILabel 艺术家姓名标签 { 获取;放; }

    void ReleaseDesignerOutlets ()
    {
        if (artistNameLabel != null) {
            artistNameLabel.Dispose ();
            artistNameLabel = null;
        }
    }
}

最后,这是一个非常基础的 XIB - 它只有一个标签

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
        <dependencies>
            <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
        </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="AlbumCell">
            <connections>
                <outlet property="view" destination="2" id="RRd-Eg-VrN"/>
            </connections>
        </placeholder>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <view contentMode="scaleToFill" id="2">
            <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
            <subviews>
                <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="Label" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="5">
                    <rect key="frame" x="279" y="95" width="42" height="21"/>
                    <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                    <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                    <nil key="highlightedColor"/>
                </label>
            </subviews>
            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
        </view>
    </objects>
</document>

下面是我从父 ViewController 创建单元格对象实例的代码

public partial class NewReleasesView : MvxCollectionViewController
{
    public NewReleasesView()
        : base(new UIKit.UICollectionViewFlowLayout()
        {
            ItemSize = new CoreGraphics.CGSize(250,200),
            ScrollDirection = UICollectionViewScrollDirection.Vertical
        })
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        CollectionView.RegisterNibForCell(AlbumCell.Nib, AlbumCell.Key);
        var source = new MvxCollectionViewSource(CollectionView, AlbumCell.Key);
        CollectionView.Source = source;

        var set = this.CreateBindingSet<NewReleasesView, NewReleasesViewModel>();
        set.Bind(source).To(vm => vm.NewReleases);
        set.Apply();
        CollectionView.ReloadData();

        var viewModel = this.ViewModel as IMvxViewModel;
        viewModel.Start();
    }

}

【问题讨论】:

  • 检查您的网点。当您从代码中删除 outlet 属性但没有从 Storyboard 中删除连接时,就会发生这种情况。
  • 您能发布更多关于异常消息的详细信息吗?那是什么课?关键是什么?你有堆栈跟踪吗?您的应用在哪一行崩溃了?
  • @Paulw11,我在描述中添加了编码示例和调用堆栈。谢谢!!
  • 异常表示您有一个 NSObject 的实例,而不是 AlbumCell。你能显示你在哪里创建单元实例的代码吗?
  • @Paulw11,我已经用 ViewController 代码更新了上面的帖子,该代码具有创建单元对象的配置。

标签: ios xamarin visual-studio-2015 mvvmcross


【解决方案1】:

看起来 Visual Studio 将插座放置在错误的位置。请参阅下面我输入“Outlet was here”的地方。这就是生成 UI 标签的地方。我手动将其删除,然后进入 Visual Studio 中的 XIB 编辑器并在设计器中重新添加插座名称。那时,它把它放在了我标记为“它应该在什么时候出现”的正确位置。

我不确定最初是什么导致了这种行为,但这种解决方法确实起到了作用。感谢所有帮助过我的人。

<objects>
    <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="AlbumCell">
        <connections>
             ***OUTLET WAS HERE***
        </connections>
    </placeholder>
    <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
    <view contentMode="scaleToFill" id="1" customClass="AlbumCell">
        <rect key="frame" x="0.0" y="0.0" width="250" height="250"/>
        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
        <color key="backgroundColor" customColorSpace="calibratedWhite" colorSpace="calibratedWhite" white="0" alpha="1"/>
        <subviews>
            <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" text="Label" lineBreakMode="tailTruncation" minimumFontSize="10" id="4" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" customClass="UILabel">
                <rect key="frame" x="53" y="20" width="177" height="21"/>
                <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                <color key="textColor" colorSpace="calibratedWhite" white="1" alpha="1"/>
                <nil key="highlightedColor"/>
            </label>
        </subviews>
        <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
        <size key="freeformSize" width="600" height="600"/>
        <connections>
            ***WHEN IT SHOULD HAVE BEEN HERE***
            <outlet property="artistname" destination="4" id="name-outlet-4"/>
        </connections>
    </view>
</objects>

【讨论】:

  • 这很有帮助,我现在明白为什么我会收到错误并且可以在将来修复它。谢谢!
【解决方案2】:

感谢@Paulw11q 的指导,让我发现了问题。

我必须调用以下行以及RegisterNibForCell,以便MVVMCross 知道它需要创建的对象类型。我看到的所有MVVMCross 样本中都缺少该行。

CollectionView.RegisterClassForCell(typeof(AlbumCell), AlbumCell.Key);

【讨论】:

  • 原来这并没有解决问题。这导致我的 Cell 派生类创建时没有错误,但作为回报,XIB 未加载。我还是卡住了:(
猜你喜欢
  • 2018-12-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
相关资源
最近更新 更多