1.使用Swift反射将同样类型的obj2中非空字符串属性复制到obj1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class AegReflectUtils { static func copyObj2ToObj1(_ obj1: NSObject, _ obj2: NSObject) { let mirror = Mirror(reflecting: obj2) for child in mirror.children { guard let propertyName = child.label else { continue } if shouldSkip(property: propertyName) { continue } guard let stringValue = child.value as? String, !stringValue.isEmpty else { continue } obj1.setValue(stringValue, forKey: propertyName) } } private static func shouldSkip(property: String) -> Bool { let blacklist = ["Companion", "serialVersionUID"] return blacklist.contains(property) } }
|
2.对象代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @objc class AegDevice: NSObject { @objc var name: String? @objc var room: String? @objc var model: String? @objc var mac: String? @objc var ip: String? @objc var version: String? @objc var type: String? = nil @objc var status: String? = nil
var desc: String { return "name: \(name ?? ""), room: \(room ?? ""), model: \(model ?? ""), mac: \(mac ?? ""), ip: \(ip ?? ""), version: \(version ?? ""), type: \(type ?? ""), status: \(status ?? "")" } }
|
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private func test() { let obj2 = AegDevice() obj2.name = "test" obj2.room = "room" obj2.model = "model"
let obj1 = AegDevice() obj1.mac = "mac" obj1.ip = "ip" obj1.version = "version" obj1.type = "type" obj1.status = "status"
AegReflectUtils.copyObj2ToObj1(obj1, obj2) ASLog(obj1.desc) ASLog(obj2.desc) }
|