objc_setAssociatedObject 如何使用选择器 (SEL)?

How to use selector (SEL) with objc_setAssociatedObject?

我能否以某种方式将 SEL 类型的参数与 objc_setAssociatedObject 一起使用而不将其转换为 NSString 类型?

目前我正在使用这段代码: objc_setAssociatedObject(thirdPartyObject, &kSelectorKey, NSStringFromSelector(selector), OBJC_ASSOCIATION_RETAIN);

转换为 NSString 有效,但感觉不对。必须有更合适的解决方案。

OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

第三个参数必须是对象类型。所以,是的,您需要这种转换。

试试这个。
在我的示例中,我已经通过 indexpath 你必须用你的参数替换

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    yourCustomeCell *aCell;
    NSString *aStrIdentifier = @"yourIdentiFier";
    aCell = (yourCustomeCell *)[tableView dequeueReusableCellWithIdentifier:aStrIdentifier];

    //you have to set your indexpath
    objc_setAssociatedObject(aCell.btnUpload_or_Add, @"objBtn", indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [aCell.YourButton addTarget:self action:@selector(yourButtonActiontapped:) forControlEvents:UIControlEventTouchUpInside];

    return aCell;
}

-(IBAction)yourButtonActiontapped:(UIButton *)sender{

    NSIndexPath *aIndPath =  objc_getAssociatedObject(sender, @"objBtn");
    NSLog(@"row:%@",aIndPath.row);
}

also you have to import #import <objc/runtime.h>