【问题标题】:Objective C subclassed iVar doesn't take the same pointer type?Objective C 子类化 iVar 不采用相同的指针类型?
【发布时间】:2016-03-08 00:53:28
【问题描述】:

我遇到了一个我不明白的错误。我将 UICollectionViewCell 子类化如下:

CollectionViewCell.h

@interface CollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *txtLabel;

在视图控制器中,我使用如下:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    CollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    UICollectionViewCell *cellOne = [collectionView cellForItemAtIndexPath:indexPath];

使用 CollectionViewCell 的第一次调用会发出警告,第二次不会发出警告,它们都是同一个类。选中单元格后更改单元格并访问其中的数据。

CollectionViewCell 行的警告是“不兼容的指针类型正在使用 'UICollectionViewCell *' 类型的表达式初始化 'CollectionViewCell *'

如果它们都是同一个类,唯一的区别是 iVar txtLabel,为什么它们的工作方式会不同?

我正在尝试使用 indexPath 获取单元格。我假设这些单元格有一些存储空间,您可以使用传入的 indexPath 访问这些单元格。

第一季度。我是否正确地假设我可以通过使用传入的 indexPath 来获取单元格?

第二季度。为什么当他们都是同一个班级时,一个电话有效而另一个电话无效?

【问题讨论】:

    标签: ios objective-c pointers nsindexpath


    【解决方案1】:
    CollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    

    方法-cellForItemAtIndexPath:被定义为返回UICollectionViewCell。编译器不知道实际返回的是CollectionViewCell

    你必须向下转型告诉编译器你知道你在做什么

    CollectionViewCell *cell = (CollectionViewCell *) [collectionView cellForItemAtIndexPath:indexPath];
    

    这将删除警告。但这只是一个警告。它会警告您可能出现的错误,但代码会正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多