【发布时间】:2015-04-03 16:37:58
【问题描述】:
我的项目中有一部分,我必须用自定义类填充许多数组和字典。在此过程中,内存使用量当然开始增加。但是最后,当我使用 removeAllObjects 从任何地方删除项目时,内存使用量保持在同一水平,而不是减少到起始值。
我做了一个简化的代码,它当然没有意义,但重现了我得到的原始问题:
标题:
@interface ViewController : UIViewController
@property (strong, nonatomic) NSMutableArray *imageArray;
@property (strong, nonatomic) NSTimer *timer;
- (IBAction)start:(id)sender;
- (IBAction)stop:(id)sender;
@end
实施:
@implementation ViewController
....
- (IBAction)start:(id)sender
{
[self.loadingIndicator startAnimating];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(addImages) userInfo:nil repeats:YES];
}
- (IBAction)stop:(id)sender
{
[self.loadingIndicator stopAnimating];
[self.timer invalidate];
[self.imageArray removeAllObjects];
}
- (void)addImages
{
int i = 0;
while (i < 500)
{
UIImage *image = [UIImage imageNamed:@"test.png"];
[self.imageArray addObject:image];
i++;
}
}
...
@end
问题:
当我调用 start 时,1 分钟后内存使用量从 3.9 MB 增加到 58 MB。很好,但是当我调用 stop 时,调用 removelAllObjects 时,它仍然保持相同的值,58 MB。
我做错了什么?我正在使用 ARC!
【问题讨论】:
-
你有没有在模拟器中尝试过“触发内存警告”,看看是不是只有在有内存压力时才释放内存?或者当你通过创建一个新数组来重置数组时会发生什么,或者只是将 nil 分配给 self.imageArray
-
我现在在模拟器上试过了,奇怪的是它工作得很好,从列表中删除所有对象后,内存使用量减少到原始值,甚至没有触发内存警告。那么问题是为什么这种行为在真实设备上有所不同?顺便说一句,将数组或设置重置为 nil 会产生相同的行为。
标签: objective-c memory-leaks nsmutablearray