获取自定义 NS 对象的属性数组的简单方法?

Easy way to get array of properties of a custom NS object?

我有一个具有某些属性的 NSObject,如:

public class Contact: NSObject {

var first: String = ""
var last: String = ""
var title: String = ""
//and so forth
}

是否有一种简单的方法可以将对象的单个实例(即一个联系人)的对象属性值获取到数组中,例如:

{"Bob","Smith","Vice President"}

我似乎找不到一种直接的方法来做到这一点。提前感谢您的任何建议。

穴居人方式:

public class Contact: NSObject {

  var first: String = ""
  var last: String = ""
  var title: String = ""

  var values: [String] {
    return [first, last, title]
  }
}

一种更有用的方式,它允许您序列化为 NSKeyedArchiver、JSONEncoder 或其他任何方式:

public class Contact: NSObject {

  var first: String = ""
  var last: String = ""
  var title: String = ""

  var values: NSDictionary {
    return [
      "first": first,
      "last": last,
      "title": title
    ]
  }
}

无论哪种方式,最简单的方法是手动抓取您感兴趣的状态属性。

查找对象属性值的最佳方法是使用苹果提供的镜像 API。您可以获得

的属性值

Example Code

public class Contact: NSObject {
var first: String = ""
var last: String = ""
var title: String = ""
//and so forth

var values: [String] {
    return Mirror(reflecting: self).children.map {[=10=].value as? String ?? ""}
}