使用objectforkey的OpenURL

时间:2015-04-16 17:36:56

标签: objective-c uitableview cell

我正在尝试使用表格单元格内的UIButton从json文件打开一个URL。问题是当按下按钮时应用程序崩溃,这给我一个错误,说明

  

由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [UIButton objectForKey:]:无法识别的选择器发送到实例0x786c2310'

这是使用的代码。 objectforkey:@"URL"链接到json文件,其字符串为" http://www.facebook.com"。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ItemCell";
    DCItemCell *cell = (DCItemCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // If we don’t get returned a reusable cell we allocate and initialize one with a custom frame that positions it at the very top left corner of its container and makes it the same width and height as our cell.
    if (cell == nil)
    {
        cell = [[DCItemCell alloc] initWithFrame:CGRectMake(0, 0, kCellWidth, kCellHeight)];
    }

    NSDictionary *currentItem = [self.items objectAtIndex:indexPath.row];
    [cell.thumbnailbutton addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.thumbnail.image = [UIImage imageNamed:[currentItem objectForKey:@"ImageName"]];

    return cell;
}


-(void) btnAction:(id) sender 
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[sender objectForKey:@"URL"]]];
}

2 个答案:

答案 0 :(得分:1)

中的sender
-(void) btnAction:(id) sender {

是您的thumbnailButton,而不是JSON文件本身。你可以

A)将URL存储在DCItemCell本身的属性中,并实现该类中按钮的目标方法。

B)将按钮的cell.thumbnailButton.tag属性设置为indexPath.row,以便您知道单击了哪一行。

答案 1 :(得分:0)

btnAction:方法作为sender的参数将是来自单元格的UIButton。您正尝试使用objectForKey:通过将该消息发送到UIButton来尝试访问该属性,而tableView:didSelectRowAtIndexPath:没有实现此方法!这就是导致崩溃的原因。

这里有几种选择。一个好主意是实现UITableView的{​​{1}}委托方法,然后抓住你的模型对象,该对象应该包含URL。