美文网首页
swift类 通过 NSClassFromString 获取

swift类 通过 NSClassFromString 获取

作者: 笨的很想飞 | 来源:发表于2023-04-19 09:32 被阅读0次

    1.swift 版本

    static  public  func getClassFromString(_ classString: String) -> AnyClass? {
            
            guard let bundleName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else {
                return nil
            }
              
            let classPath = bundleName + "." + classString;
                
            var anyClass: AnyClass? = NSClassFromString(classPath)
            if (anyClass == nil) {
                anyClass = NSClassFromString(classString)
            }
            return anyClass
        }
    

    2.OC 版本

    +(Class)getClassFromString:(NSString *)classString{
        
        Class anyClass = NSClassFromString(classString);
        if(anyClass == nil){
            NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
            NSString *bundleName = [infoDict objectForKey:@"CFBundleName"];
            NSString *classPath = [NSString stringWithFormat:@"%@.%@",bundleName,classString];
            anyClass = NSClassFromString(classPath);
        }
        return anyClass;
    }
    

    相关文章

      网友评论

          本文标题:swift类 通过 NSClassFromString 获取

          本文链接:https://www.haomeiwen.com/subject/zxzkjdtx.html