开发者

should variable be released or not? iphone-sdk

In the following piece of code (from a book) data is an NSDictionary *data; defined in the header (no property).

In the viewDidLoad of the controller the following occurs:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *keys = [NSArray arrayWithObjects:@"home", @"work", nil];
    NSArray *homeDVDs = [NSArray arrayWithObjects:@"Thomas the Builder", nil];
    NSArray *workDVDs = [NSArray arrayWithObjects:@"Intro to Blender", nil];
    NSArray *values = [NSArray arrayWithObjects:homeDVDs, workDVDs, nil];
    data = [[NSDictio开发者_运维知识库nary alloc] initWithObjects:values forKeys:keys];

}

Since I am really new to objective-c can someone explain to me why I do not have to retain the variables keys,homeDVDs,workDVDs and values prior exiting the function? I would expect prior the data allocation something like:

[keys retain];
[homeDVDs retain];
[workDVDs retain];
[values retain];

or not? Does InitWithObjects copies (recursively) all objects into a new table?

Assuming we did not have the last line (data allocation) should we release all the NSArrays prior exiting the function (or we could safely assumed that all NSArrays will be autoreleased since there is no alloc for each one?)

Thanks!!!!


In Core Foundation, most of static calls to methods such as arrayWithObjects: return autoreleased instances, which means you don't need to (and even must not!) release it by yourself.

So the situation after your code is executed is that all arrays you created with arrayWithObjects: calls are autoreleased, but are retained when added to other array or dictionary. So homeDVDs and workDVDs are retained when added to the values array, and keys and values arrays are both retained when added to the data dictionary.

So you don't need to explicitly release your arrays, but you'll need to release your data dictionary at some point (perhaps in dealloc method implementation).


NSDictionary copies the key field and retains the values. All your other instances are autoreleased, so you're not missing any releases or retains (assuming you release data in the dealloc method).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜