iosregexvimbatch-processingviewdidunload

Way to remove all -viewDidUnload from project's view controllers


As Apple's Official Doc said:

-viewDidUnload is deprecated in iOS 6.0. Views are no longer purged under low-memory conditions and so this method is never called.

Meanwhile, it's better to remove all -viewDidUnload implements from projects that the deployment target is iOS 6.0 or later. But removing it one by one is boring, especially you've hundreds of controllers & several projects.

So, is there any script or command that can do this batch job?


Solution

  • I figured out a command for Vim, I'm sure it'll make your life easier. ;)

    Open Vim in desired root dir (generally, it'll be your root dir of your all controller files), press Shift : to enter command-line mode, run the command below:

    :args **/*.m | argdo %s/^-\ (void)viewDidUnload\_.\{-}}\n^$\n//ge | update
    

    This will replace all

    - (void)viewDidUnload
    {
      [super viewDidUnload];
      ...
    }
    // a blank line here
    

    to empty, in other words, the -viewDidUnload snippet will be removed. But note, there's a blank line after the implement. If you don't want to include it, use

    :args **/*.m | argdo %s/^-\ (void)viewDidUnload\_.\{-}}//ge | update
    

    instead.

    Note: This will include lib files as well when you're in your project's root dir. I suggest go to your Controllers' root dir, then all files & you will be happy with the result. ;)


    Tip:

    After that, you'd better check whether all -viewDidUnload were removed, run the command below on terminal of your desired root dir:

    $ find . -type f -iname "*.m" -exec grep -i "viewDidUnload" {} +
    

    It should result with no output. Otherwise, some targets missed, you can locate it easily cause it'll list all files that not managed correctly, then just remove it manually (This might happen if your - (void)viewDidLoad is -(void)viewDidLoad without a space, or something else).

    Finally, you can run

    $ git diff -b --color-words
    

    to see the result. Enjoy it! ;)


    Further reading about the command


    Reference