Luda Luda - 2 months ago 20
Objective-C Question

dequeueReusableCellWithReuseIdentifier doesn't go through init nor initWithCoder functions

When creating cells for

UICollectionView
,
dequeueReusableCellWithReuseIdentifier
doesn't go through
init
nor
initWithCoder
function of
CategoryView
.

The view is creating, it has a proper type (
CategoryView
) but
init
nor
initWithCoder
of
CategoryView
is not called, so essential functionality is not executed. Is there some other init in this senario?

- (CategoryView *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

CategoryView *cell = [cv dequeueReusableCellWithReuseIdentifier:@"CategoryView" forIndexPath:indexPath];
[cell someConfiguration];
return cell;
}

Rob Rob
Answer

In this case, the problem was that the base class was not specified for your cell prototype in Interface Builder. So make sure the base class is set:

enter image description here

Then, when you call dequeueReusableCellWithReuseIdentifier, using the storyboard identifier you specified in the prototype cell, it calls initWithCoder when the cell is first instantiated. If the cell scrolls out of view and is later re-used for another NSIndexPath, the prepareForReuse is called:

@interface CategoryView : UICollectionViewCell

@end

@implementation CategoryView

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        NSLog(@"init");
    }
    return self;
}

- (void)prepareForReuse {
    [super prepareForReuse];
    NSLog(@"reuse");
}

@end
Comments