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.
我的团队已决定新文件应该用swift编写,我发现在Objective-C对象中使用KVC在Swift对象上设置属性有一个奇怪的问题。
My Objective-C sets a property like so: [textObject setValue:0.0 forKey:@"fontSize"]
我的Objective-C设置了如下属性:[textObject setValue:0.0 forKey:@“fontSize”]
My Swift object (textObject
) has a custom setter/getter for this property.
我的Swift对象(textObject)具有此属性的自定义setter / getter。
var fontSize: CGFloat? {
get {
return internalTextGraphic?.fontSize
}
set {
internalTextGraphic?.fontSize = newValue
}
}
However, if I set a breakpoint in the set
, it never gets hit.
但是,如果我在集合中设置断点,它永远不会被击中。
I have Objective-C objects that also get this same call, and I just implement -setFontSize
, and the execution enters properly.
我有Objective-C对象也得到同样的调用,我只是实现-setFontSize,并且执行正确进入。
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.
为什么我似乎无法通过-setValueForKey进入我的set方法?我100%确认textObject存在且类型正确。
EDIT:
Martin R is correct, I had to make the type a non-optional. This is my working code:
编辑:马丁R是正确的,我不得不使类型不可选。这是我的工作代码:
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
}
}
}
1 个解决方案
#1
8
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
原因是Swift可选的struct或enum(在你的情况下是CGFloat?)在Objective-C中是不可表示的(你不会在生成的“Project-Swift.h”头文件中看到该属性)。如果使用@objc显式标记属性,那么这将变得更加明显,然后您将收到错误消息
error: property cannot be marked @objc because its type cannot be represented in Objective-C
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?
.
如果将属性类型更改为非可选的CGFloat,则KVC将按预期工作。它也适用于可选的类类型,例如NSNumber?。
#1
8
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
原因是Swift可选的struct或enum(在你的情况下是CGFloat?)在Objective-C中是不可表示的(你不会在生成的“Project-Swift.h”头文件中看到该属性)。如果使用@objc显式标记属性,那么这将变得更加明显,然后您将收到错误消息
error: property cannot be marked @objc because its type cannot be represented in Objective-C
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?
.
如果将属性类型更改为非可选的CGFloat,则KVC将按预期工作。它也适用于可选的类类型,例如NSNumber?。