Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mirror not working in Swift when iterating through children of an Objective-C object

I have a very strange issue related to using Mirror in Swift. I am iterating over all of the properties in a class called Test:

let test = Test()
let mirror = Mirror(reflecting: test)
for i in mirror.children {
    ...
}

If I implement my Test class in Swift, I have three values in children that is iterated over:

class Test: NSObject {
    var device: NSNumber!
    var version: NSNumber!
    var application: NSString!
}

However, if I implement the Test class in Objective C, I get zero children:

@interface ObjectCTest : NSObject

@property (nonatomic, strong) NSNumber *device;
@property (nonatomic, strong) NSNumber *version;
@property (nonatomic, strong) NSString *application;

@end

Does anyone know what might be going on? I'm starting to think it might be something to do with Xcode project settings, as I have other projects that this works for. Any suggestions are appreciated!

like image 745
lehn0058 Avatar asked Jan 06 '23 13:01

lehn0058


1 Answers

Mirror does not seem to work with Objective-C classes. But, you can use the class_copyPropertyList function to retrieve all the properties from an Objective-C class.

var outCount : UInt32 = 0
let properties = class_copyPropertyList(ObjectCTest.self, &outCount)

print(outCount)

for i : UInt32 in 0..<outCount
{
  let strKey : NSString? = NSString(CString: property_getName(properties[Int(i)]), encoding: NSUTF8StringEncoding)

  let attrs : NSString? = NSString(CString: property_getAttributes(properties[Int(i)]), encoding: NSUTF8StringEncoding)

  print(strKey)
  print(attrs)
}
like image 104
Christian Abella Avatar answered Jan 13 '23 22:01

Christian Abella