ppaulojr
ppaulojr

Reputation: 3647

NSClassFromString misbehaving and caching class

I have a class X and several classes X1,X2,X3,X4 that are descendants of X

I have a NSArray with the name of the classes and I'm using it to iterate:

_classnames = @[@"X1",@"X2",@"X3",@"X4"];

And then:

- (UITableViewCell *)tableView:(UITableView *)tableView 
                                   cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * identifier = @"cellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier 
                                   forIndexPath:indexPath];
    if (!cell) {
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:identifier];
    }

    X * xshared = [NSClassFromString(_classnames[indexPath.row]) shared];
    cell.textLabel.text = [xshared title];
    return cell;
}

EDIT: Funny thing is:

for (NSString * s in _classnames) {
    NSLog(@"%@",NSClassFromString(s));
}

works outside the tableView call

But then all NSClassFromString return the class X1

Am I missing something?

Upvotes: 2

Views: 94

Answers (1)

ppaulojr
ppaulojr

Reputation: 3647

I found the error and I'm posting here just for the sake of completion.

In class X I was declaring shared as

+ (instancetype)shared {
    static id _shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shared = [self new];
    });

    return _shared;
}

And I was not implementing shared in the child classes.

Adding shared to the child classes solved the problem. The reason it returns always the first class instantiated is pretty obvious but I didn't see.

Upvotes: 2

Related Questions