I’m reading in an XML file from an “XMLReader” class, which I create and call from the app delegate. Inside the XMLReader class, I’m creating an “AppState” object which contains the data read in the XML. The XMLReader autoreleases the AppState class when it creates it. When the XMLReader is done, the app delegate assigns the the AppState instance to its own variable, retains it, and releases the XMLReader class. The code in the app delegate looks like this:
XMLReader *xmlReader = [[XMLReader alloc] init];
[xmlReader parseXMLData: data];
appState = xmlReader.appState; // <== xmmReader creates appState with autorelease
[appState retain];
[xmlReader release];
I’m a bit unclear as to whether there is a convention that you shouldn’t need to retain assigned objects within the class to which the object is assigned. In this case it’s required due to the autorelease – if I don’t retain it in the app delegate, the app crashes. Is there a better way? e.g. I could create the AppState in the delegate and set it on XML reader. That way the alloc and release could be in the same class. What’s the typical way to do this?
There is a better way – simply create a (retain) @property for your appState object, synthesize it and assign your xmlReader.appState to self.appState instead.
This is retain the new value and assign it to your appState object.
You can then release it/set it to nil in the App delegate’s dealloc method.
And implement
Then assign with