Using a UINavigationItem subclass in code

I have a custom UINavigationController subclass, one that uses an equivalent UINavigationItem subclass containing an additional two stored properties. The UINavigationController subclass displays additional UI elements in its root view depending on the value of these two new properties.


However, while I can specify the UIViewControllers to use this UINavigationItem subclass in a XIB/Storyboard, I work on a team that has a very strong "no XIB/Storyboard" policy. As such, I'm trying to find a way to specify that my programmatic UIViewControllers should use this custom subclass for their navigationItems, but navigationItem is a get-only property.


Without using XIBs/Storyboards, is there a way I can force this particular cluster of UIViewControllers to utlize this custom UINavigationItem subclass?


(DISCLAIMER: I would strongly prefer NOT to fall back on associated objects or thread locals, if possible.)

According to the documentation, you would need to subclass all of the UIViewControllers to return a UINavigationItem of the custom subclass from their "navigationItem" property override. There's no apparent requirement to invoke super in the getter, so you should have a free hand.

Any potential edge cases to watch out for? I'm always a little leery about abusing blind spots created by dynamic dispatch.

I don't think so. It looks to me that this is the expected solution to your problem.


It also seems safe enough if the experiment escapes the lab. If these custom views return subclassed navigation items to a nav controller that's not expecting the subclass, your additional properties should just be ignored. The only danger there would be if there are any memory management implications to ignoring those extra properties, but I wouldn't expect that to be a problem.

Using a UINavigationItem subclass in code
 
 
Q