What should I do if a large amount of view in remove results in a sharp increase in memory?

this is the method of traversing and removing the specified type subview:

- (void)refresh {
    for (UIView *view in self.subviews) {
        if ([view isMemberOfClass:[GoodListThemeView class]] || [view isMemberOfClass:[SingleGoodsThemeView class]]) {
            [view removeFromSuperview];
        }
    }
}

when this method is called, the memory changes are as follows:

if I commented out the code [view removeFromSuperview]; , there would be no such phenomenon of memory exploding and then plummeting.

I guessed that a large number of temporary objects were generated in that for loop, so I used autoreleaserpool:

- (void)refresh {
    for (UIView *view in self.subviews) {
        @autoreleasepool {
            if ([view isMemberOfClass:[GoodListThemeView class]] || [view isMemberOfClass:[SingleGoodsThemeView class]]) {
                [view removeFromSuperview];
            }
        }
    }
}

but memory suddenly soars and then falls.

who can provide some ideas?

Ios
Mar.12,2021

  1. needs the function of @ autoreleasepool . Its real function is that if a temporary variable is created in the package statement, it can be released in advance. Obviously, your usage situation does not conform to this principle, so it is invalid
  2. .
  3. for. In. Fast enumeration should not change the elements in the collection in principle, so maybe you can try block traversal (but I think it should be not too different. for in see a lot of examples. The), for loop is not considered because it will result in an extra temporary copy
  4. .
  5. removeFromSuperview does not mean that the memory will be released. The correct statement is that it will be released at a later point in time (usually the next event loop) . If you want to release it in time, you can manually empty it. view = nil;

now that you see the memory skyrocketing, have you used Instruments to take a look at the Allocation trace? for this period of time? What objects have been created or what malloc has occurred during this time?


I guess the for loop is the removeFromSuperview method is an asynchronous and time-consuming operation. Need to take up a large amount of memory, find a way to remove one and then remove the next. Get a Synchronize or something.


[view.subviews makeObjectsPerformSelector:@selector (removeFromSuperview)];


change to block to do, discard the loop, write an iterator function and recursively


memory surge. I suspect it is caused by the delay of the removeFromSuperview method. It may be caused by the memory surge caused by the continuous execution of the for loop before it takes effect. The solution is to leave it empty manually.

Menu