【问题标题】:exception says sent to an object that is not KVC-compliant for the "frame" property异常说发送到“框架”属性不符合 KVC 的对象
【发布时间】:2016-09-29 11:44:09
【问题描述】:

在我的自定义 UITableViewCell 中,我正在做这样的事情。

-(void)checkHeight
{
    if (self.frame.size.height < self.expandedHeight) {
        self.lblReasontitle.hidden=YES;
    }
    else
    {
        self.lblReasontitle.hidden=NO;
    }
}
-(void)watchFrameChanges
{
    if (!isObserving) {

        [[NSNotificationCenter defaultCenter] addObserver:self forKeyPath:@"frame" options: (NSKeyValueObservingOptionNew |NSKeyValueObservingOptionInitial) context:nil];
        isObserving=true;
    }
}
-(void)ignoreFrameChanges
{
    if (isObserving) {
        [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"frame"];
    }
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"frame"]) {
        [self checkHeight];
    }
}

但我遇到了这个异常。

由于未捕获的异常 NSUnknownKeyException 导致应用程序终止,原因:[addObserver: forKeyPath:@"frame" options:5 context:0x0] 被发送到“frame”属性不符合 KVC 的对象。

我不知道那个异常是什么以及如何解决它。 请帮我。 谢谢

【问题讨论】:

    标签: ios uitableview nsnotificationcenter addobserver


    【解决方案1】:

    从上面的代码我想你想做一对一的交流。如果是这样,请使用 KVO 而不是 NSNotification。

    像这样替换代码,

    -(void)checkHeight
    {
        if (self.frame.size.height < self.expandedHeight) {
            self.lblReasontitle.hidden=YES;
        }
        else
        {
            self.lblReasontitle.hidden=NO;
        }
    }
    -(void)watchFrameChanges
    {
        if (!isObserving) {
    
            [self addObserver:self forKeyPath:@"frame" options: (NSKeyValueObservingOptionNew |NSKeyValueObservingOptionInitial) context:nil];
            isObserving=true;
        }
    }
    -(void)ignoreFrameChanges
    {
        if (isObserving) {
            [self removeObserver:self forKeyPath:@"frame"];
        }
    }
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"frame"]) {
           [self checkHeight];
        }
    }
    

    【讨论】:

      【解决方案2】:

      默认情况下,UIKit 元素不兼容 KVO - 直到文档化。因此,你得到了这个例外。尝试注册一些与框架相关的值,它应该可以工作。

      【讨论】:

      • 感谢您的回答。如何注册?
      • 你不能为 UIKit 元素做这件事。你做得很好,而不是框架,尝试向其中发送一些其他的东西......比如 frame.size 等
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多