Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching an object to a UIActionSheet

A view's 'delete' button is pressed. The view belongs to a view controller, which handles the button press. However, that view controller is a child of a container view controller, so it sends its delegate a message that a deletion was requested, and includes the object that should be deleted.

The delegate (the parent view controller) receives the notification and presents a UIActionSheet to confirm the deletion. It also makes itself the delegate of that action sheet.

The user confirms the deletion, and parent view controller is ready to delete the object. Except it has to do this in actionSheet:didDismissWithButtonIndex:. By that point, it no longer knows which object was passed down from the child view controller.

Is there a way to attach an object to the alert sheet so that when it's dismiss action is fired, that object can be retrieved?

like image 879
Ben Packard Avatar asked Nov 18 '25 06:11

Ben Packard


1 Answers

The Objective-C 2.0 runtime supports associated objects - using this API, you can, euh, associate object with each other using a key-value method. Example:

id someObject = // however you obtain it
objc_setAssociatedObject(theActionSheet, "AssociatedDelegateObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

// later try to get the object:
id someObject = objc_getAssociatedObject(theActionSheet, "AssociatedDelegateObject");
// process the associated object, then release it:
objc_removeAssociatedObjects(theAlertSheet);

Edit: it seems that you don't really need to shoot a bird usign a cannon and use runtime functions, since the same class/object that manages the alert sheet cares about the delegation also, so you could just assign it temporarily to an instance variable. However, this approach may be easier to extend later when your object model gets more complicated.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!