开发者

Memory Management on Views in Use

开发者 https://www.devze.com 2023-02-13 07:55 出处:网络
I\'m just learning how to code for the iPhone using Objective-C, and I don\'t quite understand why a view开发者_如何学Python controller needs to be released when its in use?

I'm just learning how to code for the iPhone using Objective-C, and I don't quite understand why a view开发者_如何学Python controller needs to be released when its in use?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

Thanks in advance


The navigation controller retained the detail view controller already, therefore, the retain count is 2 at that point. The release will make the retain count 1.


The dl;dr of what I have below is this: take care of your local memory management, don't worry about needing to manage the memory of API classes. They manage their own memory.

Some things to remember with Objective-C memory management:

  • The cocoa touch classes are responsible for retaining things you give it. Add a subview to a view? The view retains it on its own. Pushing a view controller onto a navigation controller? The navigation controller retains the view controller until it is popped off the stack.
  • Conversely, each time you call alloc, copy, new and/or retain there must be a corresponding release or autorelease. In the code above, you called alloc to make your view controller, giving it a retain count of 1 that you are responsible for releasing at some point.
  • If you use properties that are objects with dot notation and the property is a copy or retain property (usually what you want), don't do this:

    self.property = [[WhateverObject alloc] init];

instead, do this:

self.property = [[[WhateverObject alloc] init] autorelease;
0

精彩评论

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