John Fowler
John Fowler

Reputation: 3271

How to mass-add a 2 letter prefix / namespace to Objective-C Project?

I am using XCode, and have an Objective-C, iOS project with 200+ source files including 2 storyboards and 10 xibs. This project does not use a 2 letter prefix for its classes. Now, its classes need to be added to another project which also does not use 2 letter namespacing. There will be plenty of naming conflicts.

What is the best way to add a 2 or 3 letter prefix to every source file and class in an XCode project? Are there any automated tools to do this?

Upvotes: 4

Views: 788

Answers (1)

John Fowler
John Fowler

Reputation: 3271

Since no one else is submitting an answer to my question, here is a brute-force solution I have created using UNIX Shell Scripts.

Step #1:
Create a "rename_classes.txt" file where each line contains a class name from/to pair separated by one or more tabs. Example:

MyClassA   ZZMyClassA
MyClassB   ZZMyClassB
MyClassC   ZZMyClassC

Step #2:
Copy and paste the following into a shell script, and then execute the script from the directory containing the XCode project:

#!/bin/bash

PROJECT_DIR=.
RENAME_CLASSES=rename_classes.txt

#First, we substitute the text in all of the files.
sed_cmd=`sed -e 's@^@s/[[:<:]]@; s@[[:space:]]\{1,\}@[[:>:]]/@; s@$@/g;@' ${RENAME_CLASSES} `
find ${PROJECT_DIR} -type f \
    \( -name "*.pbxproj" -or -name "*.h" -or -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.xib" -or -name "*.storyboard" \) \
    -exec sed -i.bak "${sed_cmd}" {} +

# Now, we rename the .h/.m files
while read line; do
    class_from=`echo $line | sed "s/[[:space:]]\{1,\}.*//"`
    class_to=`echo $line | sed "s/.*[[:space:]]\{1,\}//"`
    find ${PROJECT_DIR} -type f -regex ".*[[:<:]]${class_from}[[:>:]][^\/]*\.[hm]*" -print | egrep -v '.bak$' | \
    while read file_from; do
         file_to=`echo $file_from | sed "s/\(.*\)[[:<:]]${class_from}[[:>:]]\([^\/]*\)/\1${class_to}\2/"`
         echo mv "${file_from}" "${file_to}"
         mv "${file_from}" "${file_to}"
    done
done < ${RENAME_CLASSES}

Note the following:

  • This script will update all references to classes found in the Project File, XIB files, storyboard files, .h, .m, .mm, & .cpp source files.
  • For each modified file, a backup file with the original contents will be created named "[filename].bak".
  • This script only renames .h, .m, & .mm files. .xib files and Storyboards will need to be renamed by hand.
  • 'PROJECT_DIR' can be set to another directory if desired.
  • 'RENAME_CLASSES' should point to the file created in Step #1.
  • If there are groups named the same as classes that are being renamed, the groups will be renamed in the project file as well.
  • I have used this script on 4+ projects, and it has worked beautifully.

If no one has a better answer at the end of the bounty period, I'll accept this answer (my own).

Upvotes: 4

Related Questions