开发者

NSAutoreleasePool in UIViewController life cycle

I am working in an app for iPad. It presents several views, so I have to be careful with the memory management.

My problem is related with the autorelease objects. I would like to associate a NSAutoreleasePool to each view controller. Something like this:

MyViewController.h

@interface MyViewController: UIViewController

@property (nonatomic, retain) NSAutoreleasePool *myPool;

MyViewController.m

@implementation MyViewController

@synthesize myPool;

- (void) viewDidLoad {
    myPool = [[NSAuroteleasePool alloc] init];    
}


- (void) dealloc {
    [myPool drain];
}

A NSAutoreleasePool can not be used as a property. I would like to achieve a behavior similar to this. Any idea? Thank you in advance.

EDIT

Thank you for your answers. In response to your questions (I can not answer my question yet):

The viewController will do a lot more of things, will respond to events, etc, etc. What I would like is, after all these operations, release what should be autoreleased. Extending the example:

MyViewController.h

@interface MyViewController: UIViewController

@property (nonatomic, retain) NSAutoreleasePool *myPool;

MyViewController.m

@implementation MyViewController

@synthesize myPool;

- (void) viewDidLoad {
    myPool = [[NSAuroteleasePool alloc] init];    
}


- (IBAction) whatEver: (id) sender {
    UIImage *img = [UIImage imageWithData: ...];
    NSString *str = @"MyString";
    ...
}

- (void) dealloc {
    [myPool drain];
}

Here, what would happen with the string and the image? I guess they are retained in the pool, aren't they? I could wait for the rel开发者_StackOverflowease pool in the main method but I guess it will be drained when the application ends.


It is completely unnecessary to create local autorelease pools in such case. Are you sure you know how autorelease pools work? What exactly are you trying to achieve?

(After editing the question.) Ah, I see. You don’t understand Cocoa memory management, please read the guide. The main autorelease pool gets drained after each runloop iteration, which makes your local autorelease pools completely useless. Custom autorelease pools are rarely needed, mostly just when you create a lot of objects in a loop or when you are doing stuff in your own thread.

To put it shortly, forget about extra autorelease pools and everything will work fine.


This is a very bad idea. Read Using Autorelease Pools and the Memory Management Policy first.


No need to create the Local autorelease pool.in main.m file you have NSAutoreleasepool it will take care of it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜