I’m subclassing UIView to make a custom view by overriding drawRect:. I need to find a point that is equal to 10 percent of the View’s width. Of course, that distance is trivial to calculate (self.bounds.size.width/10.0f). I would like to cache this value, that is, I want to store this value in an instance variable to avoid having to calculate it on every single drawRect:.
Inside what method would I store this value? I was thinking about just saving the variable’s value while in initWithFrame:, but then the cached value would be out of sync with the view’s width after any sort of resize.
Any thoughts on what the best place to cache the view’s width is… and if it is even ok to do so?
You can store the value in an ivar and (re)compute it in layoutSubviews.
However, this is an obvious case of premature optimization. You should focus on writing good code, and optimize when the need becomes apparent. In fact, this “optimization” could even have a negative impact on your app’s performance: is it more expensive to divide two numbers or to look up the value of an ivar?