简体   繁体   English

NSClassFromString 行为异常和缓存类

[英]NSClassFromString misbehaving and caching class

I have a class X and several classes X1,X2,X3,X4 that are descendants of X我有一个班级X和几个班级X1,X2,X3,X4 ,它们是X后代

I have a NSArray with the name of the classes and I'm using it to iterate:我有一个带有类名称的NSArray ,我正在使用它进行迭代:

_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 calltableView调用之外工作

But then all NSClassFromString return the class X1但随后所有NSClassFromString返回类X1

Am I missing something?我错过了什么吗?

I found the error and I'm posting here just for the sake of completion.我发现了错误,我在这里发布只是为了完成。

In class X I was declaring shared as在班级X我宣布shared

+ (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.而且我没有在子类中实现shared

Adding shared to the child classes solved the problem.添加shared到子类解决了这个问题。 The reason it returns always the first class instantiated is pretty obvious but I didn't see.它总是返回实例化的第一个类的原因很明显,但我没有看到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM