Lazy WOComponent ivar initialization

How do you setup instance variables if they need to be initialized after their WOComponent is fully formed?

Overiding the awake() method happens too early, so you’re usually left overriding later in the request-response loop *. Here is a nice simple alternative pattern that I use all the time.

  1. Create your instance variables (I like to make them protected at least)
    protected NSArray _myThings;
  2. Give your ivars public accessor methods
    public NSArray myThings() {
    	return _myThings;
    }
     
    public void setMyThings(NSArray array) {
    	_myThings = array;
    }
  3. Modify the getter method so it follows this pattern:
    public NSArray myThings() {
    	if (_myThings == null) {
    		//initialize _myThings here
    	}
    	return _myThings;
    }

This pattern works really well for setting up things like display groups or arrays of fetched objects. If you bind to the accessor method in your WOComponent, the first time the method is hit, the values will be initialized. Very clean and easily understood. I like it a lot 🙂

* You do know the stages of the request-response loop don’t you? If you don’t buy Chuck’s book. Do it now. I’ll wait…