0

I'm using this open source library which is a wrapper on AddressBook.framework. There's no method for deleting contact, so I'm gonna use default ABAddressBookRemoveRecord. However for that I need the ABAddressBookRef.

Since it's declared in APAddressBook.m file of that APAddressBook library as @property (nonatomic, readonly) ABAddressBookRef addressBook; and I'm not able to get access to it, I wanted to write extension in Swift, containing method returning it.

So this is body of my extension:

extension APAddressBook {
    private struct AssociatedKey {
        static var addressBookRef = "addressBook"
    }

    var xo: ABAddressBook! {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.addressBookRef)
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKey.addressBookRef, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
        }
    }

    func getABAddressBook() -> ABAddressBookRef {
        return self.xo
    }

}

I've also tried using private var xoAssociationKey: UInt8 = 0 as associatedKey, but calling getABAddressBook() function always crashes with fatal error: unexpectedly found nil while unwrapping an Optional value.

What's wrong with my code? Also is there better way to solve my problem?

Adam Bardon
  • 3,829
  • 7
  • 38
  • 73

1 Answers1

0

Well maybe it's not particulary an answer to your questions but here is some thoughts.

You only know what to pass in obc_objc_getAssociatedObject because your lib is open source.

So why wouldnt you use that to fit it under your needs?

If i were you I'd just move that property to the public access. I dont find it a really worse solution than trying to access private property via obc_ methods.

Regarding your question did you try to specify addressBookRef as : NSString? Since Apple now made swift's String and NSString two different types.

s1ddok
  • 4,615
  • 1
  • 18
  • 31
  • Hi, you mean directly edit library? I surely thought about it after few hours :D but from long term perspective it's not the best solution, I'd have to do it every time they update library... that's why we have categories/extensions for I think. I don't get that String part... what does it have to do with addressBookRef? – Adam Bardon May 28 '15 at 04:43