我正在使用iPad的应用程序。它提供了几个视图,所以我必须小心内存管理。
我的问题与自动释放对象有关。我想将NSAutoreleasePool与每个视图控制器关联起来。像这样:
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];
}
NSAutoreleasePool不能用作属性。我想实现类似于此的行为。任何的想法?提前谢谢。
修改
感谢您的回答。回答你的问题(我还不能回答我的问题):
viewController将执行更多操作,将响应事件等等。我想要的是,在所有这些操作之后,释放应该自动释放的内容。扩展示例:
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];
}
在这里,字符串和图像会发生什么?我猜他们留在了游泳池里,不是吗?我可以在main方法中等待发布池,但我想它会在应用程序结束时耗尽。
答案 0 :(得分:2)
在这种情况下,完全没有必要创建本地自动释放池。您确定知道自动释放池的工作原理吗?你究竟想要实现什么目标?
(编辑问题之后。)啊,我明白了。您不了解Cocoa内存管理,请阅读the guide。每次runloop次迭代后,主自动释放池都会耗尽,这会使您的本地自动释放池完全失效。很少需要自定义自动释放池,主要是在循环中创建大量对象或在自己的线程中执行操作时。
简而言之,忘掉额外的自动释放池,一切都会正常工作。
答案 1 :(得分:1)
这是一个非常糟糕的主意。阅读Using Autorelease Pools和Memory Management Policy 第一
答案 2 :(得分:0)
无需创建本地自动释放pool.in main.m文件,您将拥有NSAutoreleasepool,它将负责处理它。