gpt4 book ai didi

ios - 在 Swift 中按名称获取实例变量

转载 作者:搜寻专家 更新时间:2023-11-01 05:41:54 26 4
gpt4 key购买 nike

我正在尝试快速复制此功能:https://stackoverflow.com/a/11774276/4102858 .我能够在 Swift 中成功地重新创建 allPropertyNames() 。但是,我在使用方法 pointerOfIvarForPropertyNamed() 执行相同操作时遇到了问题。主要原因是 Objc 解决方案使用了函数 object_getInstanceVariable(),它在 Swift 中不可用。

TLDL:我正在尝试在 Swift 中重新创建此方法:

- (void *)pointerOfIvarForPropertyNamed:(NSString *)name
{
objc_property_t property = class_getProperty([self class], [name UTF8String]);
const char *attr = property_getAttributes(property);
const char *ivarName = strchr(attr, 'V') + 1;
Ivar ivar = object_getInstanceVariable(self, ivarName, NULL);
return (char *)self + ivar_getOffset(ivar);
}

这是我现在所在的位置:

func pointerOfIvarForPropertyNamed(name: String) -> AnyObject {

func unicodeValueOfString(string: String) -> UInt32 {
for s in String(string).unicodeScalars {
return s.value
}
return 0
}

var property: COpaquePointer = class_getProperty(self.classForCoder, (name as NSString).UTF8String)
var attr: UnsafePointer<Int8> = property_getAttributes(property)
var ivarName: UnsafeMutablePointer<Int8> = strchr(attributesPointer, Int32(unicodeValueOfString("V"))) + 1

//object_getInstanceVariable() not available in Swift

}

问题:

函数 object_getInstanceVariable() 在 Swift 中不可用

我普遍缺乏使用 Objective-C 运行时的经验

最佳答案

来自 Swift 文档(强调我的):

If you have experience with Objective-C, you may know that it provides two ways to store values and references as part of a class instance. In addition to properties, you can use instance variables as a backing store for the values stored in a property.

Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly. This approach avoids confusion about how the value is accessed in different contexts and simplifies the property’s declaration into a single, definitive statement. All information about the property—including its name, type, and memory management characteristics—is defined in a single location as part of the type’s definition.

根据 pointerOfIvarForPropertyNamed 的使用方式,您可能无法将该方法直接翻译成 Swift,因为它没有 Ivars。您可以 use Key-Value Coding实现你想要的。

如果你想扩展这个方法的使用方法,我可以适当扩展我的答案。

关于ios - 在 Swift 中按名称获取实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28492622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com