假设我有以下代码行。
var instanceName = "someString"
我如何以String格式获取实例的名称,以便将其用作在NSUserDefaults中存储var的键? 所以在上面的例子中,我希望得到" instanceName"来自instanceName ...
后续问题:
如何使用字符串返回变量内容。例如。 "instanceName"
答案 0 :(得分:3)
您可以使用class_copyIvarList
(因为我知道Swift不支持可选变量)来获取类实例中的所有变量,循环遍历它们并获取名称。
var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)
for var i = 0; i < Int(propertiesCount); i++ {
var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)
}//for
<强>游乐场强>
class Myclass{
var myInteger:Int = 1
var myBoolean:Bool = false
var myString:String = "heyStr"
func printValues(){
var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)
for var i = 0; i < Int(propertiesCount); i++ {
var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)
println(propName)
}//for
}
}
var mc:Myclass = Myclass()
mc.printValues()
输出:
myInteger
myBoolean
myString
[编辑1]
Ivar
指的是Objective-C运行时:
/// An opaque type that represents an instance variable.
typealias Ivar = COpaquePointer
[编辑2]
如果你有兴趣获得价值观也会做两件事:
NSObject
a.e.继承你的cass。 class Myclass:NSObject{..}
var propValue : AnyObject! = self.valueForKey(propName)
顺便说一句,如果你想将它们存储到某些词典中,你需要先检查它们的类型。因为您将propValue
定义为AnyObject