OC memory continued to grow after using method swapping(swizzle)

26 views Asked by At

By using method exchange, the problem of NSMutableArray array out of bounds is determined.

myCode like this:

static inline void swizzleSelectorKK(Class theClass, SEL originalSelector, SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
    method_exchangeImplementations(originalMethod, swizzledMethod);
}


and call it in the load function:
+(void)load{
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        swizzleSelectorKK(NSClassFromString(@"__NSArrayM") , @selector(objectAtIndex:), @selector(kk_objectAtIndex:));
    });
}

the replace function like this:
- (id)kk_objectAtIndex:(NSUInteger)index {
    if (self.count == 0) {
        return nil;
    }
    if (index >= self.count) {
        return nil;
    }
    return [self kk_objectAtIndex:index];
}

in my viewcontroll:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.arr = [[NSMutableArray alloc]init];
    [self.arr addObject:@"this is a array"];
    [self.arr addObject:@"this 2 array"];
    [self.arr addObject:@"this 3"];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.backgroundColor = [UIColor systemBlueColor];
    [button setTitle:@"click" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(reloadDataxxx) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(200, 100, 200, 200);
    [self.view addSubview:button];
}
- (void)reloadDataxxx {
    self.index = self.index % 3;
    NSLog(@"index of is %ld data = %@", self.index, [self.arr objectAtIndex:self.index]);
    self.index ++;
}

As you continue to click, you will find that the memory continues to grow, as long as you remove the exchange method, the memory will not change.

It's been a long day. Thank you

0

There are 0 answers