实现一个简单的重用池

.h文件

//
//  THReusePool.h
//  into
//
//  Created by huant on 2019/3/29.
//  Copyright © 2019 huant. All rights reserved.
//

#import 

NS_ASSUME_NONNULL_BEGIN

@interface THReusePool : NSObject

- (UIView *)dequeReuseView;


- (void)addViewToolPool:(UIView *)view;

- (void)resetPool;
@end

NS_ASSUME_NONNULL_END

.m文件

//
//  THReusePool.m
//  into
//
//  Created by huant on 2019/3/29.
//  Copyright © 2019 huant. All rights reserved.
//

#import "THReusePool.h"

@interface THReusePool ()

@property (nonatomic, strong) NSMutableSet * waitingPool;

@property (nonatomic, strong) NSMutableSet * usingPool;

@end
@implementation THReusePool


- (instancetype)init{
    if (self = [super init]) {
        
        self.waitingPool = [NSMutableSet set];
        self.usingPool = [NSMutableSet set];
    }
    return self;
}

- (UIView *)dequeReuseView{
    
    UIView * viewPool = [self.waitingPool anyObject];
    
    if (!viewPool) {
        return nil;
    }else{
        NSLog(@"从pool中取出视图");
        [self.usingPool addObject:viewPool];
        [self.waitingPool removeObject:viewPool];
        return viewPool;
    }
}


- (void)addViewToolPool:(UIView *)view{
    NSLog(@"添加视图到pool中");

    [self.usingPool addObject:view];
}

- (void)resetPool{
    
    UIView * view = nil;
    while ([self.usingPool count]) {
        
        view = [self.usingPool anyObject];
        [self.waitingPool addObject:view];
        [self.usingPool removeObject:view];
    }
    NSLog(@"pool中可重用%lu个视图", (unsigned long)self.waitingPool.count);

}



@end

外面调用测试

   if (flag == 0) {
        flag = 1;
        for (int i = 0; i<5; i++) {
            
            UILabel * view = (UILabel *)[self.pool dequeReuseView];
            if (!view) {
                view = [UILabel new];
                [self.pool addViewToolPool:view];
            }
            view.frame = CGRectMake(0, i*20, 100, 20);
            view.text = [NSString stringWithFormat:@"%d", i];
            [self.view addSubview:view];
        }
        
    }else{
        flag = 0;
        
        for (int i = 0; i<10; i++) {
            
            UILabel * view = (UILabel *)[self.pool dequeReuseView];
            if (!view) {
                view = [UILabel new];
                [self.pool addViewToolPool:view];
            }
            view.frame = CGRectMake(0, i*20, 100, 20);
            view.text = [NSString stringWithFormat:@"%d", i];
            [self.view addSubview:view];
        }
    }
    

你可能感兴趣的:(实现一个简单的重用池)