准备看的iOS程序员的业余沙龙iOS

将iOS代码批量重命名或者替换

2018-08-10  本文已影响60人  Phelthas

被苹果审核4.3规则折腾了好几天。。。然后看到别人博客说到可以通过一些操作来避免(参考https://blog.csdn.net/MakerCloud/article/details/81006467),

但是他写的那个工具我这儿不太适用

然后还找到一些博客(https://my.oschina.net/FEEDFACF/blog/1626928)用shell脚本来执行类似的操作

本来想顺便学一下shell脚本,但项目时间很紧,所以还是用仿照第一篇博客用OC代码来写了

看了别人的工具的代码我才知道,macOS的代码是有权限修改整个基本电脑里面的文件的。

基本原理就是创建一个macOS的程序,然后在这个程序里面修改电脑的文件就行了。

(注意:是新建一个macOS的程序而不是iOS的程序,APP是运行在手机里的,所以只能修改手机里面的内容,

macOS程序是在电脑上运行的,所以能修改电脑里的内容,而APP的项目就是电脑里面的一个文件夹而已)

如图:

image.png

得到的就是一个只有一个main.m文件的 mac程序。

然后就牛X了,这里不得不感叹一下苹果的一体化水平,开发mac程序和开发iOS程序是很像的,Foundation里面的东西全部通用!

所以只需要用NSFileManager就可以直接操作文件了,而修改文件内容,就是用“ NSMutableString *content = [NSMutableString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];”取到文件内容的字符串,

用正则匹配替换,然后再用“ [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];”保存就行了。重命名更简单,就是“ [fm moveItemAtPath:path toPath:newPath error:&renameError];”,苹果里面重命名就是移动路径,跟其他Linux系统是一样的。

所以剩下的就是找到指定目录,递归的替换就行了

我这里递归的思路是:输入参数 path,判断path是否是文件夹,如果是文件夹,则遍历文件夹内容,对每个子路径执行递归函数;

如果不是文件夹,则判断该文件是否需要修改(比如是否以XXX开头,或者是.h .m .swift文件),不需要就直接返回,需要就用上面提到的方法修改。

so easy~

这里还可以顺便替换所有出现的类名,就是在重命名之前,在其他指定目录里面,递归的替换所有oldClassName为newClassName,再保存。

其实就是递归函数里面嵌套另一个递归函数,时间复杂度可能会高一点,但是这种操作对电脑来说也就是分分钟的事,我几千个文件,全部执行下来也不用1分钟。

注意:重命名文件后,还需要修改 xxx.xcodeproj/project.pbxproj文件,也是把原来的文件名替换为新的文件名。否则相当于工程文件原来的文档都丢失了但没有添加新的文件

在写这个工具之前,我已经手动重命名,替换了几个类,无聊到炸!

然后写完这个工具以后,看着我原来要改半天的东西现在不要一分钟就改好了,这怎一个爽字了得!!!

这才是程序猿的乐趣啊 哈哈~

/**
 递归的遍历指定目录,将目录中遇到的类的名字修改前缀,并替换所有项目中出现的该类名字符串
 */
void renameRecursion(NSString *path, NSString *projectPath) {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error = nil;
    NSError *renameError = nil;
    BOOL isDir = NO;
    [fm fileExistsAtPath:path isDirectory:&isDir];
    if (isDir) {
        NSArray *array = [fm contentsOfDirectoryAtPath:path error:&error];
        if (error == nil) {
            for (NSString *subPath in array) {
                NSString *newPath = [[path mutableCopy] stringByAppendingPathComponent:subPath];
                renameRecursion(newPath, projectPath);
            }
        }
    } else {
        NSString *name = [path lastPathComponent];
        NSString *className = name.stringByDeletingPathExtension;
        NSString *classExtension = name.pathExtension;
        
        
        if ([className hasPrefix:@"MT"]) {
            NSString *newClassName = [[className mutableCopy] stringByReplacingOccurrencesOfString:@"MT" withString:@"WHG"];
            NSString *newPath = [[path mutableCopy] stringByReplacingOccurrencesOfString:@"MT" withString:@"WHG"];
            
            replaceProjectClassName(className, newClassName, projectPath);
            
            NSString *settingString = [NSString stringWithFormat:@"%@.xcodeproj/project.pbxproj", projectPath];
            replaceProjectClassName(className, newClassName, settingString);
            
            [fm moveItemAtPath:path toPath:newPath error:&renameError];
            if (renameError != nil) {
                NSLog(@"renameError : %@", renameError.description);
            }
        }
    }
    
}
/**
 替换工程中所有的类名
 */
void replaceProjectClassName(NSString *oldName, NSString *newName, NSString *path) {
    @autoreleasepool {
        BOOL isDir = NO;
        NSError *error = nil;
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm fileExistsAtPath:path isDirectory:&isDir];
        if (isDir) {
            NSArray *array = [fm contentsOfDirectoryAtPath:path error:&error];
            if (error == nil) {
                for (NSString *subPath in array) {
                    NSString *newPath = [[path mutableCopy] stringByAppendingPathComponent:subPath];
                    replaceProjectClassName(oldName, newName, newPath);
                }
            }
        } else {
            NSString *name = [path lastPathComponent];
            NSString *classExtension = name.pathExtension;
            if (!([classExtension isEqualToString:@"h"] || [classExtension isEqualToString:@"m"] || [classExtension isEqualToString:@"swift"] || [classExtension isEqualToString:@"xib"] || [classExtension isEqualToString:@"storyboard"] || [classExtension isEqualToString:@"pbxproj"])) {
                return;
            }
            
            NSMutableString *content = [NSMutableString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
            if (error) {
                NSLog(@"打开文件失败:%@", error.description);
                return;
            }
            NSString *regularExpression = [NSString stringWithFormat:@"\\b%@\\b", oldName];
            
            NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:regularExpression options:NSRegularExpressionAnchorsMatchLines|NSRegularExpressionUseUnixLineSeparators error:nil];
            NSArray<NSTextCheckingResult *> *matches = [expression matchesInString:content options:0 range:NSMakeRange(0, content.length)];
            [matches enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [content replaceCharactersInRange:obj.range withString:newName];
            }];
            
            
            [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
        }
        
    }
    
    
}
上一篇 下一篇

猜你喜欢

热点阅读