First look at the parameters that this method receives
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
The associated object, as shown in the following example, is associated to the Uialertview
- The key value of the object to be associated, typically set to static, to get the value of the associated object
- The value of the object to be associated, the type of ID received from the interface, so that any object can be associated
- The agreement used in the association, there are assign,retain,copy and other agreements, specific reference to the official documents
The following is a simple example of how to use Uialertview
Use scene: Click on a cell in UITableView, this time pop up a uialertview, and then uialertview disappear when the cell information, we get the cell's Indexpath
The first step:
#import <objc/runtime.h>static char kUITableViewIndexKey;- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{......UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"这里是xx楼" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];//然后这里设定关联,此处把indexPath关联到alert上objc_setAssociatedObject(alert, &kUITableViewIndexKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);[alert show];
}
Step Two:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (buttonIndex == 0) { NSIndexPath *indexPath = objc_getAssociatedObject(alertView, &kUITableViewIndexKey); NSLog(@"%@", indexPath); }}
Simple use of associated objects in iOS Objc_setassociatedobject