如何将选择器 (SEL) 与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);
}

您还必须导入#import <objc/runtime.h>

最新更新