开发者

Memory allocation design question

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开发者_StackOverflow中文版 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.

@interface XXX : AppDelegate
{
}
@property (nonatomic, retain) XXXXX appState

And implement

@implementation XXX
@synthesize appState;

Then assign with

self.appState = xmlReader.appState;


If you make appState a property of your class, then you can assign to it using:

self.appState = xmlReader.appState;

The synthesised setter method will retain it automatically (provided that you declare the property as retain, or, if appState is a string, it is also conventional to declare the property as copy).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜