2016-03-08 68 views
1

我收到一個錯誤,我不明白。我繼承UICollectionViewCell如下:Objective C子類iVar不採用相同的指針類型?

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的行是「不兼容的指針類型初始化‘CollectionViewCell *’與類型的表達式‘UICollectionViewCell *’

如果它們都相同的類,唯一的區別是IVAR txtLabel,他們爲什麼會以不同的方式工作?

我想獲得使用indexPath的單元格。我假設有一些存儲這些單元格,您可以使用傳入的indexPath訪問這些單元格。

Q1。我正確地假設我可以通過使用傳入的indexPath來獲取單元格嗎? Q2302。爲什麼一個電話會工作而另一個不是同一個班級?

回答

1
CollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; 

方法-cellForItemAtIndexPath:被定義爲返回UICollectionViewCell。編譯器不知道實際返回的是CollectionViewCell

你必須垂頭喪氣告訴編譯器,你知道你在做

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

這是什麼會刪除該警告。這只是一個警告。它警告你可能有錯誤,但代碼會正常工作。