objc_getAssociatedObject返回null

时间:2015-07-23 17:39:06

标签: ios objective-c

我正在尝试使用objc_setAssociatedObject

传递对象

我正在尝试使用以下代码传递Evento

Evento *evento = (Evento*)[secAtt objectAtIndex:indexPath.row]; 
objc_setAssociatedObject(evento, @"evento", self, OBJC_ASSOCIATION_RETAIN);

以后我尝试使用以下代码获取此evento

Evento *evento = objc_getAssociatedObject(self, "evento");

返回nil

编辑:更多代码:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    NSString *sectionTitle = [sectionsTitles objectAtIndex:indexPath.section];
    NSArray *secAtt = [attractions objectForKey:sectionTitle];

    Evento *evento = (Evento*)[secAtt objectAtIndex:indexPath.row];
    objc_setAssociatedObject(self, @"evento", evento, OBJC_ASSOCIATION_RETAIN);

    NSString *tipoEntretenimento = evento.entretenimento.tipo.descricao;
    NSLog(@"tipo %@", tipoEntretenimento);
    UIImageView *imgCategoria = (UIImageView *)[cell.contentView viewWithTag:30];
   //[imgCategoria setContentMode:UIViewContentModeScaleAspectFit];
    if([tipoEntretenimento isEqualToString:@"Bares"])
        [imgCategoria setImage:[UIImage imageNamed:@"bares.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Crianca"])
        [imgCategoria setImage:[UIImage imageNamed:@"crianca.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Guloseimas"])
        [imgCategoria setImage:[UIImage imageNamed:@"guloseimas.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Restaurantes"])
        [imgCategoria setImage:[UIImage imageNamed:@"restaurantes.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Teatro"])
        [imgCategoria setImage:[UIImage imageNamed:@"teatro.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Shows"])
        [imgCategoria setImage:[UIImage imageNamed:@"shows"]];
    else if ([tipoEntretenimento isEqualToString:@"Dança"])
        [imgCategoria setImage:[UIImage imageNamed:@"danca.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Concertos"])
        [imgCategoria setImage:[UIImage imageNamed:@"concerto.png"]];
    else if ([tipoEntretenimento isEqualToString:@"Cinema"])
        [imgCategoria setImage:[UIImage imageNamed:@"cinema.png"]];


    UIFont *roboto = [UIFont fontWithName:@"Roboto-Bold" size:16];
    UILabel *lblNomeEvento = (UILabel *)[cell.contentView viewWithTag:10];
    lblNomeEvento.text = evento.entretenimento.nome;
    lblNomeEvento.font = roboto;

    Agenda *agenda = nil;
    if([evento.listaAgendas count] > 0)
        agenda = (Agenda *)[evento.listaAgendas objectAtIndex:0];

    NSLog(@"agenda %@", agenda.description);

    UIImageView *imgevento = (UIImageView *)[cell.contentView viewWithTag:20];
    [imgevento setContentMode:UIViewContentModeScaleAspectFit];
    [imgevento setImage:[UIImage imageNamed:@"pin.png"]];

    UIButton *btnCompartilhar = (UIButton *)[cell.contentView viewWithTag:40];
    [btnCompartilhar.titleLabel setHidden:YES];
    btnCompartilhar.titleLabel.text = evento.entretenimento.nome;
    [btnCompartilhar addTarget:self action:@selector(compartilharClick:) forControlEvents:UIControlEventTouchDown];


    UIButton *btnFavoritar = (UIButton *)[cell.contentView viewWithTag:50];
    [btnFavoritar addTarget:self action:@selector(favoritarClick:) forControlEvents:UIControlEventTouchDown];
    return cell;
}

以后我试图获取对象时:

-(void) compartilharClick:(id)sender {
    Evento *evento = (Evento *)objc_getAssociatedObject(self, "evento");

    UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"Compartilhar:" delegate:self cancelButtonTitle:@"Cancelar" destructiveButtonTitle:nil otherButtonTitles:
                            @"Facebook",
                            @"Google+",
                            @"Twitter",
                            @"Outros",
                            nil];
    popup.tag = 1;
    [popup showInView:[UIApplication sharedApplication].keyWindow];
}

4 个答案:

答案 0 :(得分:1)

objc_setAssociatedObject的第一个参数应该是self(第三个应该是evento

答案 1 :(得分:1)

进行关联时,selfevento混淆了,请尝试:

objc_setAssociatedObject(self, @"evento", evento, OBJC_ASSOCIATION_RETAIN);

Reference Link

编辑: objc_setAssociatedObject(你正在使用“evento”)的关键是需要一个唯一的指针。如果您检查参考链接,他们建议使用选择器作为密钥,因为它保证是唯一的。

定义您的密钥一次(char *const AssoicateKey = "evento";)它应该开始工作。

此外,除非您的表中只有1行,否则您的代码将无效。每次使用单元格时,您都会覆盖关联。检索它时,最后一个单元格的对象将出列。您可以将对象与按钮相关联,并将其从发件人处理到您的操作以使其正常工作。

答案 2 :(得分:1)

这里的问题可能是因为当函数需要const void *key

时使用NSString作为键

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

尝试在您的实施上方添加static char *EventToKey = "EventToKey";

然后将objc_getAssociatedObjectobjc_setAssociatedObject的使用更改为

objc_setAssociatedObject(self, EventToKey, evento, OBJC_ASSOCIATION_RETAIN);

objc_getAssociatedObject(self, EventToKey);

答案 3 :(得分:0)

您使用的密钥必须是两个调用上的相同指针。不是具有相同值的字符串(如果你传递“evento”两次,指针可以是不同的),并且绝大多数是一个NSString * @“evento”和一个C字符串“evento”就像你一样。

最简单的方法是创建一个静态变量并传递地址。