NSString swizzle initWithString: 总结

起因

在维护老项目的时候,线上出了个关于字符串创建为nil的crash


NSString swizzle initWithString: 总结_第1张图片
错误信息

收到反馈后,第一反应是找到 initWithString: 方法添加判断参数是否为 nil 保护一下,如下:

    if (name != nill) {
        _userName = [[NSString alloc] initWithString:name];
       
    }else{
     
        _userName =@"";
       
    }

然后我查了下该工程中 initWithString: 方法,有50+,且都未做保护,emmmm...略微思考后,想到我可以用 Swizzle 黑魔法,直接 hook 到 NSString 的  initWithString: 方法,然后替换成自己加过判断的方法,一步搞定,屠龙宝刀点击就送,美滋滋~

object Runtime Swizzle

添加关于 NSString 的 category,重写 load 方法 :

+ (void)load{

    Class class = [self class];
    SEL originalSelector = @selector(initWithString:);
    SEL swizzledSelector = @selector(my_InitWithString:);   
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    //先调用 class_addMethod,为了防止swizzle掉父类的方法导致后面的swizzle出现隐藏的bug(有可能子类A 替换到方法func:,然后子类B 又把func替换回来)
    BOOL didAddMethod =
    class_addMethod(class,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
   
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
   
}

- (instancetype)my_InitWithString:(NSString *)aString{
    if (aString == nil) {
        return @"";
    }else{
        return [[NSString alloc] my_InitWithString:aString];
    }
}

啪啪啪一顿操作猛如虎,运行 test demo,初始化nil 依然 crash,且在替换的方法中断点,居然不会走!emmmmm....难道是自己代码写错了?断点跟踪调试发现 swizzle 成功了,但是却没有调用修改后的方法,查阅资料后找到一篇类似的问题,关于 NSMutableArray 的方法替换,类比到 NSString 中应该也是适用的,在上代码前,我们先了解一下 NSString 的继承结构,

NSString swizzle initWithString: 总结_第2张图片
NSString继承关系

其中 NSPlaceholderString , __NSCFConstantString 等叫做类簇(Class Cluster),大概类似于 C++ 中的虚基类的东西,作用呢就是 NSString 把方法的具体实现放在隐藏的私有子类(也就是类簇),然后对外只暴露部分简单的 API 接口。

hook 准则

资料查到这里,大概问题就明白了,最开始我在 hook 方法的时候,改变的是 NSSting 内的,在调用中,其实真正使用到的是 NSSting  隐藏子类(既类簇)中的实现,这时我们只要准守:谁调用hook谁 的原则,直接生成对象,然后再对其 hook,则不会出错了,hook 方法时一般有三种常见情况:

1.普通对象方法

NSString *str = [[NSString alloc] init];

        Method originalMethod = class_getInstanceMethod([str  class],@selector(substringFromIndex:));

    Method swizzledMethod = class_getInstanceMethod([str class], @selector(my_substringFromIndex));

        if (class_addMethod([str class],@selector(substringFromIndex:),method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod)) ) {

        /*swizzing super class instance method, added if not exist */        class_replaceMethod([str class],@selector(my_substringFromIndex),method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));            } else {

        method_exchangeImplementations(originalMethod, swizzledMethod);

    }

2.init 方法(这个也就是我项目中需要替换的方法)

    NSString *str = [NSString alloc];

Method originalMethod = class_getInstanceMethod([str class], @selector(initWithString:));

Method swizzledMethod = class_getInstanceMethod([str class], @selector(my_initWithString:));

        if (class_addMethod([str class],@selector(substringFromIndex:),method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod)) ) {

/*swizzing super class instance method, added if not exist */        class_replaceMethod([str class],@selector(my_substringFromIndex),method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));            } else {

        method_exchangeImplementations(originalMethod, swizzledMethod);

}

3.类方法

Method originalMethod = class_getClassMethod([NSString class], @selector(string));     Method swizzledMethod = class_getClassMethod([NSString class], @selector(my_string));

Class metacls = objc_getMetaClass(NSStringFromClass([NSString class]).UTF8String);

    if (class_addMethod(metacls,                         @selector(string),                         method_getImplementation(swizzledMethod),                         method_getTypeEncoding(swizzledMethod)) ) {

        /* swizzing super class method, added if not exist */

class_replaceMethod(metacls,@selector(my_string),method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));

            } else {

        method_exchangeImplementations(originalMethod, swizzledMethod);

}

总结

到此 hook 代码搞定,导入到 test demo 中可正常运行,搞定 ,写代码不注意,连平常最常用的 string 也会有隐藏的 bug,流下了没有技术的泪水

你可能感兴趣的:(NSString swizzle initWithString: 总结)