ViruMax ViruMax - 7 days ago 4x
Objective-C Question

How can I have two custom UICollectionViewCell classes share the same variable name

I am having two custom

classes, however, I want to create a variable of them with the same name in the same scope because all properties and all code in
method is same for both custom cells.

I want to do something like this:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

CustomCell1/CustomCell2 *cell;

if (condition) {
cell = (CustomCell1 *)[collectionView dequeueReusableCellWithReuseIdentifier:kCustomCell1Identifier forIndexPath:indexPath];
} else {
cell = (CustomCell2 *)[collectionView dequeueReusableCellWithReuseIdentifier:kCustomCell2Identifier forIndexPath:indexPath];

// Remaining code is same for both custom cells
cell.property1 = value1;
cell.property2 = value2;
//lot of code
cell.property100 = value100;

return cell;

My purpose behind this is that I don't want to repeat all that remaining code. I know that creating common custom cell class and writing this condition in that common class might be the solution but in that how can I pass condition variable to custom class before that class gets initialized. Because I think we can't initialize (alloc init) UICollectionViewCell.

Is this possible with the conditional(ternary) operator?


You can create a base(parent) collectionviewCell class

@interface BaseCollectionViewCell : UICollectionViewCell 
//Add the common methods(can add common IBOulet and IBAction) and implement them.

Now you can create new collection view cell which is derived from BaseCollectionViewCell as:

@interface ChildCell : BaseCollectionViewCell
//add methods which are specific to the ChildCell as the methods of    
//BaseCollectionViewCell is already available via inheritance.

same way you can created another collection view cell as:

@interface ChildCell2 : BaseCollectionViewCell
//add methods which are specific to the ChildCell2 as the methods of    
//BaseCollectionViewCell is already available via inheritance.

Now ChildCell and ChildCell2 gets all the methods of BaseCollectionViewCell.

Register your collection view cells to these classes along with separate reuse identifier. Use following code to dequeue the cell.

 BaseCollectionViewCell *cell;

  if (condition) {

  ChildCell *cell1 = (ChildCell *)[collectionView      
  //call cell1's specific properties if needed.
  cell = (BaseCollectionViewCell *) cell1;

  } else {

   ChildCell2 cell2 = (ChildCell2 *)[collectionView 
   dequeueReusableCellWithReuseIdentifier:kCustomCell2Identifier forIndexPath:indexPath];
  //call cell2's specific properties if needed.
  cell = (BaseCollectionViewCell *) cell2;

//call common methods here.