Reputation: 3
This is my code in ViewController.m file,
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"%f",[self usedMemory]);
NSMutableArray *array= [[NSMutableArray alloc]init];
for (int i = 0; i < 100; i++) {
NSMutableData *data = [NSMutableData dataWithLength:10000];
[array addObject:data];
}
NSLog(@"%f",[self usedMemory]);
for (int i = 0; i < 100; i++) {
[array removeObjectAtIndex:0];
}
NSLog(@"%f",[self usedMemory]);
}
Here is the usedMemory
method:
- (double)usedMemory
{
task_basic_info_data_t taskInfo;
mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
kern_return_t kernReturn = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&taskInfo,
&infoCount);
if (kernReturn != KERN_SUCCESS
)
{
return NSNotFound;
}
return taskInfo.resident_size / 1024.0 / 1024.0;
}
Here is the result:
2015-01-26 22:39:00.058 audio_memory_test[9050:874963] 25.011719
2015-01-26 22:39:00.060 audio_memory_test[9050:874963] 26.312500
2015-01-26 22:39:00.060 audio_memory_test[9050:874963] 26.312500
Why has memory not been released when I deleted objects in the array? What has the removeObjectAtIndex
method done? How can I release this memory?
Upvotes: 0
Views: 563
Reputation: 131491
As others have said, the problem is that you're creating auto-released objects. Here is a change you could make to your code so your objects would actually be released:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"%f",[self usedMemory]);
//all autoreleased objects created inside the braces
//of the @autorleasepool directive will be released
//when we leave the braces
@autoreleasepool
{
NSMutableArray *array= [[NSMutableArray alloc]init];
for (int i = 0; i < 100; i++) {
NSMutableData *data = [NSMutableData dataWithLength:10000];
[array addObject:data];
}
NSLog(@"%f",[self usedMemory]);
for (int i = 0; i < 100; i++) {
[array removeObjectAtIndex:0];
}
}
NSLog(@"%f",[self usedMemory]);
}
Upvotes: 0
Reputation: 52622
All because [NSMutableData dataWithLength: ] returns an autoreleased object, so you get exactly the expected behaviour.
To fix this: Either use [[NSMutableData alloc] initWithLength: ] or use an autorelease pool.
Upvotes: 2
Reputation: 14030
When you call [self usedMemory]
after the final loop, your objects are still held in memory. The autorelease pool to which they belong hasn't yet been drained; this generally happens when you leave the scope of your source code and the system takes control again.
Upvotes: 3