Simple use of associated objects in iOS Objc_setassociatedobject

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.