2

I am trying to replicate this functionality in swift: https://stackoverflow.com/a/11774276/4102858. I was able to successfully recreate allPropertyNames() in Swift. However, I'm having trouble doing the same with the method pointerOfIvarForPropertyNamed(). The main reason is that the Objc solution uses the function object_getInstanceVariable(), which isn't available in Swift.

TLDL: Im trying to recreate this method in 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);
}

This is where I'm at now:

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

}

Problems:

The function object_getInstanceVariable() is unavailable in Swift

My general lack of experience using Objective-C runtime

Community
  • 1
  • 1
WaltersGE1
  • 813
  • 7
  • 26

1 Answers1

0

From the Swift docs (emphasis mine):

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.

Depending on how pointerOfIvarForPropertyNamed is used, you may not be able to literally translate that method into Swift, since it doesn't have Ivars. You may be able to use Key-Value Coding to achieve what you want.

If you want to expand on how this method is used, I can expand my answer appropriately.

Community
  • 1
  • 1
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287