为什么我不能使用从Objective-C对象到Swift属性的KVC? [英] Why can I not use KVC from an Objective-C object to a Swift Property?

查看:198
本文介绍了为什么我不能使用从Objective-C对象到Swift属性的KVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的团队决定应该快速编写新文件,我发现在Objective-C对象中使用KVC在Swift对象上设置属性是一个奇怪的问题.

My team has decided that new files should be written in swift, and I am seeing an odd problem with using KVC in an Objective-C object to set a property on a Swift object.

我的Objective-C设置如下属性:[textObject setValue:0.0 forKey:@"fontSize"]

My Objective-C sets a property like so: [textObject setValue:0.0 forKey:@"fontSize"]

我的Swift对象(textObject)为此属性提供了一个自定义的setter/getter.

My Swift object (textObject) has a custom setter/getter for this property.

   var fontSize: CGFloat? {
      get {
         return internalTextGraphic?.fontSize 
      }
      set {
            internalTextGraphic?.fontSize = newValue
      }
   }

但是,如果我在set中设置了一个断点,它将永远不会被击中.

However, if I set a breakpoint in the set, it never gets hit.

我有一些Objective-C对象也得到了同样的调用,我只是实现了 -setFontSize,并且执行正确进入.

I have Objective-C objects that also get this same call, and I just implement -setFontSize, and the execution enters properly.

为什么我似乎无法通过-setValueForKey进入我的set方法? 我100%确认textObject存在并且是正确的类型.

Why can't I seem to get into my set method through -setValueForKey? I have 100% confirmed the textObject is exists and is the correct type.

编辑:
Martin R是正确的,我不得不将类型设为非可选.这是我的工作代码:

EDIT:
Martin R is correct, I had to make the type a non-optional. This is my working code:

   var fontSize: CGFloat {
      get {
         var retFontSize: CGFloat = 0.0
         if let fontSize = internalTextGraphic?.fontSize {
            retFontSize = fontSize
         }
         return retFontSize
      }
      set {
         if let textGraphic = internalTextGraphic {
            textGraphic.fontSize = newValue
         }
      }
   }

推荐答案

原因是Swift可选结构或枚举(在您的情况下为CGFloat?) 在Objective-C中无法表示(并且您不会看到该属性 在生成的"Project-Swift.h"头文件中).这变得更加明显 如果您标记该物业 @objc明确地显示,然后您将收到错误消息

The reason is that a Swift optional struct or enum (in your case CGFloat?) is not representable in Objective-C (and you won't see that property in the generated "Project-Swift.h" header file). That becomes more obvious if you mark the property explicitly with @objc, then you'll get the error message


error: property cannot be marked @objc because its type cannot be represented in Objective-C

如果将属性类型更改为非可选的CGFloat 然后KVC会按预期工作.它也可以与可选的 类类型,例如NSNumber?.

If you change the property type to the non-optional CGFloat then KVC works as expected. It would also work with an optional class type, such as NSNumber?.

这篇关于为什么我不能使用从Objective-C对象到Swift属性的KVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆