Thursday, 9 May 2019

NSObject classes inside Extensions have undefined behaviors?

So, I have a textfield where I setup its delegate. Most of the time it would work as expected, shouldChangeCharacters is called but very few times shouldChangeCharacters is not called.

Now, I thought this could just be a race condition but it only happens on some clean & build runs. And when it does happen, it is very consistent, even if the instance is recreated it still happens consistently. That's why I've ruled it out as a race issue, and think of it as an undefined behavior during compile/machine code creation.

So, my question is do I violate Objc and Swift runtime with how my extensions and protocol conformations are setup? If so, how to resolve?

class LabelAndTextFieldView{
   let textField: UITextField
   var delegate: LabelAndTextFieldViewDelegate?{ //strong so it would not dealloc
      didSet{
          textField.delegate = delegate
      }
   }
}


extension LabelAndTextFieldView{
   class LabelAndTextFieldViewDelegate: NSObject{
      //some methods unrelated to uitextfieldDelegate
   }  


   class AmountFormattingTextFieldDelegate: LabelAndTextFieldViewDelegate{
      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         //disallow if not numeric
      }

   }


}

extension LabelAndTextFieldView.LabelAndTextFieldViewDelegate: UITextFieldDelegate{
  //other uitextfield delegate methods EXCEPT shouldChangeCharactersInRange
}





//code assignment

class SomeVC{
   @IBOutlet weak var labelTextFieldView: LabelAndTextFieldView!


   override func viewDidLoad(){
      super.viewDidLoad()
      labelTextFieldView.delegate = AmountFormattingTextFieldDelegate() //this will not dealloc because intended strong on delegate

   }
}




from NSObject classes inside Extensions have undefined behaviors?

No comments:

Post a Comment