背景:

从购物车进入商品详情页,然后从商品详情页又进入购物车,如此循环,不断压栈,最终会导致app崩溃,so,保留最后几个购物车和商品详情页,把超过一定数量的页面剔除掉!

- (void)goBackPage {
NSArray *vcArray = [getDelegate().masterNavigationController viewControllers];
NSArray* reversedArray = [[vcArray reverseObjectEnumerator] allObjects];
NSMutableArray *trueArray = [[NSMutableArray alloc] init];
NSInteger cartCount = 0;
NSInteger detaCount = 0;
for (JXBaseController *vcName in reversedArray) {
NSString *vcString = NSStringFromClass([vcName class]);
if ([vcString isEqualToString:@"JXGoodsDetailPageViewController"]) {
if (detaCount < 2) {
detaCount ++;
[trueArray addObject:vcName];
}
}else if ([vcString isEqualToString:@"JXCartViewController"]) {
if (cartCount < 2) {
cartCount ++;
[trueArray addObject:vcName];
}
}else{
[trueArray addObject:vcName];
}
}
NSArray* newVcArray = [[trueArray reverseObjectEnumerator] allObjects];
UINavigationController *masterNavigationController = getDelegate().masterNavigationController
;
[masterNavigationController setViewControllers:newVcArray animated:NO];
JXPopViewController();
}

进一步封装下:

//screenArray:要删选的对象 screenCount:保留次数
- (NSArray *)getNewArrayWithOldArray:(NSArray *)oldArray screenArray:(NSArray *)screenArray screenCount:(NSInteger)screenCount{
NSArray* reversedArray = [[oldArray reverseObjectEnumerator] allObjects];
NSMutableArray *trueArray = [[NSMutableArray alloc] init];
NSMutableArray *countArray = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < screenArray.count; i++) {
NSNumber *initCount = @(0);
[countArray addObject:initCount];
}
for (JXBaseController *vcName in reversedArray) {
NSString *vcString = NSStringFromClass([vcName class]);
for (NSInteger i = 0; i < screenArray.count; i++) {
NSString *screenStr = [screenArray objectAtIndex:i];
NSNumber *initCount = [countArray objectAtIndex:i];
if ([screenStr isEqualToString:vcString]) {
if ([initCount integerValue] < screenCount) {
[trueArray addObject:vcName];
}
}else{
[trueArray addObject:vcName];
}
}
}
NSArray* newVcArray = [[trueArray reverseObjectEnumerator] allObjects];
return newVcArray;
}