0

I am setting my associated object in my cellForRowAt: method like this:

objc_setAssociatedObject(cell.changeBtn, &self.appointmentHandle, appt, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
cell.changeBtn.addTarget(self, action: #selector(self.changeButtonTouch(sender:)), for: UIControlEvents.touchUpInside)

However, in the button touch method I do this:

func changeButtonTouch(sender:UIButton) {            
    let assObj = objc_getAssociatedObject(sender, &self.appointmentHandle)
    let appt = assObj as! CHRAppointment
    let changeControl = CHRAppointmentConfirmController()
    changeControl.appointment = appt           
}

My associated object there is nil every time. Why is it not retrieving the object properly?

Sulthan
  • 128,090
  • 22
  • 218
  • 270
steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • The pointer value to a variable that isn't a static or global is not guaranteed to be stable. Compare [Why UnsafeRawPointer shows different result when function signatures differs in Swift?](http://stackoverflow.com/q/42829907/2976878) – Hamish Apr 03 '17 at 19:09
  • @Hamish So how do I fix this then? I need to associate an object with a button so that I can access it in a method when it is touched. – steventnorris Apr 03 '17 at 19:14
  • Use a pointer value to a static or global stored variable – or else provide an `UnsafeRawPointer` with its own unique bit pattern. – Hamish Apr 03 '17 at 19:16
  • @Hamish Can you please provide an example of this so I can follow your answer better. Thanks. – steventnorris Apr 03 '17 at 19:17
  • Plenty of examples [here](http://stackoverflow.com/q/24133058/2976878) :) – Hamish Apr 03 '17 at 19:19
  • @Hamish I see now. If you'll write that into an answer, I'll accept. – steventnorris Apr 03 '17 at 19:25
  • I don't think I've said anything that isn't covered by a combination of the two linked Q&As, therefore I'd say closing as a duplicate is the best course of action. – Hamish Apr 03 '17 at 19:34
  • 2
    Why even bother with that? Why not use the `sender`? – Mihai Fratu Apr 03 '17 at 19:41
  • @MihaiFratu The sender doesn't have any of the information I need. It's a UIButton, and I need to access a custom object. I could extend the UIButton into a custom class, but that seems excessive. – steventnorris Apr 03 '17 at 22:06

0 Answers0