ios 关联对象运用 objc_setAssociatedObject

时间:2024-09-27 09:04:45

ios 关联对象运用 objc_setAssociatedObject

点按钮的时候,给alertView添加一个关联对象(被点击这个按钮),

objc_setAssociatedObject(alert, &kRepresentedObject,
sender,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);

在UIAlertViewDelegate中取出关联对象(被点击的按钮)

UIButton *sender = objc_getAssociatedObject(alertView,
&kRepresentedObject);
&kRepresentedObject到底是什么东西,
kRepresentedObject从哪里来
static const char kRepresentedObject;

为什么会用char??

主要代码如下 ,
#import "ViewController.h"
#import <objc/runtime.h> @implementation ViewController static const char kRepresentedObject;
#pragma mark - event response
/** 按钮事件 */
- (IBAction)doSomething:(id)sender {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Alert" message:nil
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
objc_setAssociatedObject(alert, &kRepresentedObject,
sender,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[alert show]; }
#pragma mark - UIAlertViewDelegate
/** UIAlertViewDelegate */
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
UIButton *sender = objc_getAssociatedObject(alertView,
&kRepresentedObject);
self.buttonLabel.text = [[sender titleLabel] text];
}
@end

让我们再来看看其他关联对象是如何关联的

在分类中加入了几个属性

#import <Foundation/Foundation.h>
#import "XTableViewCellItem.h" @interface NSArray (YDTableSectionView) @property (nonatomic, strong) XTableViewCellItem *sectionHeaderItem; @property (nonatomic, strong) XTableViewCellItem *sectionFooterItem; @end @interface YDtableSectionView : UIControl @property (nonatomic, strong) XTableViewCellItem *sectionItem; @end

m文件中这样实现

#import "NSArray+YDTableSectionView.h"
#import <objc/runtime.h> @implementation NSArray (YDTableSectionView) - (void)setSectionHeaderItem:(XTableViewCellItem *)sectionHeaderItem
{
objc_setAssociatedObject(self, "sectionHeaderItem", sectionHeaderItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} - (XTableViewCellItem *)sectionHeaderItem
{
return objc_getAssociatedObject(self, "sectionHeaderItem");
} - (void)setSectionFooterItem:(XTableViewCellItem *)sectionFooterItem
{
objc_setAssociatedObject(self, "sectionFooterItem", sectionFooterItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} - (XTableViewCellItem *)sectionFooterItem
{
return objc_getAssociatedObject(self, "sectionFooterItem");
} @end

用的是

"sectionFooterItem"

而非

@"sectionFooterItem"

最上面用的是

static const char kRepresentedObject;
char kRepresentedObject;说是有是“”而非@“”
static 局部,本文件访问
const 常量,不变