美文网首页
'super.init' isn't called on all

'super.init' isn't called on all

作者: 90后的晨仔 | 来源:发表于2021-03-22 22:50 被阅读0次

前几天在用swift写自定义初始化方法的时候一下子给蒙了,今天总结一下。可以看看这篇介绍的详细

  • oc 的时候我们有时候会这样自定义一个初始化方法,然后

  • .h文件中
@interface JWeakAndStrongViewController : ViewController
- (instancetype)initWithVcName:(NSString *)vcName size:(NSInteger)size;
@end

  • .m文件中
@implementation JWeakAndStrongViewController

- (instancetype)initWithVcName:(NSString *)vcName size:(NSInteger)size{
    self = [super init];
    if (self) {
        
    }
    return self;
}

  • 换成swift可以用以下几种方式


   
class JCBaseController: UIViewController {
  
    
    init(){
        super.init(nibName: nil ,bundle: nil)
           print("init()")
       }
       init(vcName: String ,size: Int) {
           super.init(nibName: nil, bundle: nil)
        print("name: + age")
       }
       convenience init(vcName : String) {
        self.init(vcName:"dada",size: 100)
       }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  }
    
  • .swift中调用
class JCHomeViewController: JCBaseController {
 
    override func viewDidLoad() {
        let superVC1 = JCBaseController()
        let superVC2 = JCBaseController.init(vcName: "码农晨仔", size: 100)
        let superVC3 = JCBaseController.init(vcName: "码农晨仔")
    }
   }

相关文章

网友评论

      本文标题:'super.init' isn't called on all

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