【问题标题】:attaching dictionary object to UITableViewCell将字典对象附加到 UITableViewCell
【发布时间】:2013-08-29 03:09:56
【问题描述】:

I would like to know if there is a way to attach a NSDictionary object to a cell that is displayed in a UITableView, so when a cell is selected I can access the NSDictionary attached to that tableviewcell.

【问题讨论】:

    标签: ios objective-c nsmutablearray nsarray nsdictionary


    【解决方案1】:

    当然,只需创建单元格的子类并添加您的字典。您也可以使用完全空的实现:

    // MyCell.h
    @interface MyCell : UITableViewCell
    
    @property (nonatomic, strong) NSDictionary* dictionary;
    
    @end
    
    // MyCell.m
    @implementation MyCell
    @end
    

    现在,如果您正在使用情节提要,请确保您设置了您的单元格类,或者如果您不使用它,请注册它,然后在您出队时设置字典并在稍后获取单元格时读取它.

    【讨论】:

    • 太棒了..现在要弄清楚如何对它们进行子类化..非常感谢。
    【解决方案2】:

    如果您将UITableViewCell 子类化并在自定义单元格中创建NSDictionary 属性,则可以实现此目的。

    假设您在某处之前设置了此属性,以下是您在选择单元格时检索它的方式:

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        MyCustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSLog(@"%@",cell.dictionary); //replace "dictionary" by the name of the property you created in the subclass
    }
    

    【讨论】:

      【解决方案3】:

      您应该努力将数据模型 (NSDictionary) 与视图 (MyCell) 分离。这就是视图控制器的用途 - 管理每个单元格和数据之间的关系。

      您的数据模型通常是 NSArray。数组中的每个元素对应于表中的一行(indexPath)。每个 NSArray 元素将为每个单元格保存一个 NSDictionary 对象(数据模型)。​​

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-24
        • 1970-01-01
        • 2017-02-09
        • 2020-04-18
        • 2012-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多