Reputation: 1260
I am trying to use use CollectionView custom cell, where I need to update the cell from the collection view cell custom class itself.
Here is the custom cell-class
Cell_Obj.h
#import <UIKit/UIKit.h>
@interface Cell_Obj : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *label;
- (void)changeImage;
- (void)updateTextLabelName:(NSString*)str;
@end
Cell_Obj.m
#import "Cell_Obj.h"
static NSString *labelTxt ;
@implementation Cell_Obj{
}
+ (void)initialize {
if (self == [Cell_Obj class]) {
labelTxt = [[NSString alloc] init];
}
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)awakeFromNib {
_label.text = labelTxt;
[NSTimer scheduledTimerWithTimeInterval:2.0f
target:self
selector:@selector(updateLabel)
userInfo:nil
repeats:YES];
}
- (void)updateLabel
{
NSString * txt = [NSString stringWithFormat:@"%@",labelTxt];
_label.text = txt;
}
- (void)updateTextLabelName :(NSString*)str
{
labelTxt = str;
}
@end
Where in viewCotroller I am adding the cell like,
- (void)addCell
{
Cell_Obj *cell = [[Cell_Obj alloc] init];
NSString * txt = [NSString stringWithFormat:@"%d",[GridArray count]];
[cell updateTextLabelName: txt];
[GridArray addObject:cell];
[_collection insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:[GridArray count]-1 inSection:0]]];
}
The problem with above code is when I add the first cell, the label of first cell is 0 and that's fine, but when I add the second cell and the timer call happens both cell1 and cell2 has label value 1. And it supposed to have 0,1 respectively.
And it seems like the cell object is sharing static variable upon on any update happens on already created cell, like a timer event.
Why this happening, is there any mistake in my approach?
Please let me know your valuable suggestion.
Edit
Based on below answer I have moved the static variable as instance variable,
@implementation Cell_Obj{
NSString *labelTxt ;
}
but inside updateLabel
labelTxt
is nil. Where when I debug updateTextLabelName
called before updateLabel
and the labelTxt
has correct value.
Upvotes: 1
Views: 109
Reputation: 27448
This is because collectionview resues the cell to make it memory efficient. So evrery time it will call awakeFromNib
when it deque the cell. So you should use collection view datasource methods
to update or set content of collection view controls. you should implement cellForItemAtIndexPath
to set data in your label!!
Upvotes: 1
Reputation: 539
As it is an static variable, it's shared by all cell instances. The way to make it work will be to remove static from labelTxt definition.
Also, what's the meaning of it being static? If it's due to the timer, just check in the timer method that label is not null before making the update and that will solve all your problems.
Upvotes: 1