异常说发送到一个不符合 KVC 的对象 "frame" 属性

exception says sent to an object that is not KVC-compliant for the "frame" property

在我的习惯里面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];
    }
}

但是我遇到了这个异常。

Terminating app due to uncaught exception NSUnknownKeyException, reason: [ addObserver: forKeyPath:@"frame" options:5 context:0x0] was sent to an object that is not KVC-compliant for the "frame" property.

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

默认情况下,UIKit 元素不符合 KVO - 直到记录。因此,您将收到此异常。尝试注册一些与框架相关的值,它应该可以工作。

从上面的代码我认为你想做一对一的交流。如果是这样,请选择 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];
    }
}