I am busy converting my Objective C code to ARC (Automatic reference counting), and ran into the following issue:
Cast of ‘NSInteger’ (aka ‘int’) to ‘SomeRandomObject’ is disallowed with ARC.
Now in our application we’ve (unfortunately) been using the tag NSInteger property e.g. located on UITextField, UISwitch etc, to link objects to controls.
e.g.
Field *field = [[Field alloc] init...
UITextField *textField = [[UITextField alloc]....
textField.tag = (NSInteger)field;
sooo when the code reaches an event you can simply do this
UITextField *textField = (UITextField*)sender;
Field *field = (Field*)textField.tag; // ARC hates this
What would be a more standard/better way to achieve this?
A better way would be to subclass UITextField and add the properties you want it to have. If you absolutely need to add properties to an object whose class you can’t control, you can use
objc_setAssociatedObject()and friends — it’s kind of low-level and maybe a bit hacky, but certainly less so than overloading thetagproperty.