How to add userInfo to a UIAlertView?

You could try subclassing UIAlertView to add the field, or store a reference in your delegate class instead. But the most general way to attach any object to any other object is to use objc_setAssociatedObject.

To do so, you have to #import <objc/runtime.h>, and you need an arbitrary void * that is used as a key (the usual trick is to declare a static char fooKey; in your .m file and use its address). Then you can attach the object like this:

objc_setAssociatedObject(alertView, &fooKey, myDictionary, OBJC_ASSOCIATION_RETAIN);

In this case, myDictionary will be retained for the life of the alertView and will be released when the alertView is deallocated.

To retrieve your associated object later, use the logically named objc_getAssociatedObject.

NSDictionary *myDictionary = objc_getAssociatedObject(alertView, &fooKey);

It returns nil if there was no association set. To break the association, just use objc_setAssociatedObject to associate a new value for the same object and key; nil can be used to break the association without associating a new object.

Other values for the type of association besides OBJC_ASSOCIATION_RETAIN are listed here.

Leave a Comment