简体   繁体   中英

iOS NSMutableArray removeObjectAtIndex

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?

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.

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.

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM