Object-c Associated Object
In my opinion, the function of oc Association is to associate two objects and obtain them when they are used (my project is associated with an attribute in UITableView)
Example:
-(Void) viewDidLoad {[super viewDidLoad]; UIButton * button = [UIButton buttonWithType: UIButtonTypeCustom]; button. frame = CGRectMake (100,100,100,100); [button setTitle: @ join test forState: UIControlStateNormal]; [button setTitleColor: [UIColor blackColor] forState: UIControlStateNormal]; [button addTarget: self action: @ selector (buttonTap) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: button];}-(void) buttonTap {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ message: @ How (are) you doing delegate: self cancelButtonTitle: @ Not bad otherButtonTitles: @ Fine, nil]; void (^ block) (NSInteger) = ^ (NSInteger buttonIndex) {if (buttonIndex = 0) {NSLog (@ buttonIndex: 0) ;}else {NSLog (@ buttonIndex: 1) ;}}; objc_setAssociatedObject (alert, key, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC); [alert show];}-(void) alertView :( UIAlertView *) alertView clickedButtonAtIndex :( NSInteger) buttonIndex {void (^ block) (NSInteger) = values (alertView, key); block (buttonIndex);}-(void) didReceiveMemoryWarning {[super didReceiveMemoryWarning];} @ end
The preceding example shows how to associate alert and block, what object type you are associated with, what object type you are retrieving, and then use the obtained object to do what you want, the chestnut above is to retrieve the block and finish what you want to do in the block, and block it behind alert to make it easier for you to read the code (in my opinion, however, I learned from objective Object-c. I really think this is not a good one, but it is enough to understand Object Association, OBJC_ASSOCIATION_RETAIN_NONATOMIC: This is the same as (nonatomic, retain), as shown in the following table.
OBJC_ASSOCIATION_ASSIGN |
@ Property (assign)Or@ Property (unsafe_unretained) |
Specifies a weak reference to the associated object. |
OBJC_ASSOCIATION_RETAIN_NONATOMIC |
@ Property (nonatomic, strong) |
Specifies a strong reference to the associated object, and that the association is not made atomically. |
OBJC_ASSOCIATION_COPY_NONATOMIC |
@ Property (nonatomic, copy) |
Specifies that the associated object is copied, and that the association is not made atomically. |
OBJC_ASSOCIATION_RETAIN |
@ Property (atomic, strong) |
Specifies a strong reference to the associated object, and that the association is made atomically. |
OBJC_ASSOCIATION_COPY |
@ Property (atomic, copy) |
Specifies that the associated object is copied, and that the association is made atomically. |
In addition, pay attention to the issue of circular references when using block. I will not talk about this here.