Use Git in Xcode for source code version control, xcodegit
Use Git in Xcode for source code version control
In the process of application development, a very important part of the work is how to control the version of the source code. When there is a problem with the code, we need to restore the code to the original normal version. If multiple people develop a project together, the code control will be very complicated. Fortunately, developers do not need to control this by themselves, because there is a dedicated software responsible, called a version control system.
A version control system, or a modification Control System, is actually a mechanism for detecting changes to source files and saving them for future reference (software ). In addition, it can record other useful information, such as the developer who modified the code, the time when the Code was modified, the modified part, and other historical information. The version control system can compare different versions of code. If necessary, it can restore the entire project to a previous version and track harmful code to reduce product errors.
Through the version control system, developers can work on different branches of a project. When each part of the project is fully developed, they are put together to form the final version. This process is called merging. In fact, this practice is quite common in teams and software companies: each person is responsible for a part of the project, and eventually all parts are integrated to form the final product.
For individual developers, the version control system is not necessary, but we strongly recommend developers to use it, it makes it easy to convert the code between a wrong version and a working version. In fact, many developers never use similar tools. They manually Save the original project when adding new features to the project. This is actually a bad habit, because version control software can better and more efficiently complete this task.
Git is a common version control system. It was initially developed by Linus Torvalds, the father of Liunx. Git uses virtual directories, also known as repositories, to manage everything. Git can be called through command lines or desktop applications specially designed for it. If Git is unfamiliar to you, I suggest you check its related information on the Internet. More in-depth content about Git is beyond the scope of this article.
Some new features of using git are introduced from Xcode5. It integrates various features of git into a menu and provides Sub-menus for control of software merging. In the next reading, you will find that using git for version control is quite simple and quick.
The next task is to learn how to use git in Xcode and how Xcode integrates Git functions. If you think you are unfamiliar with this, I suggest you first search for related content online. In the next tutorial, I will assume that you have learned about the version control system and git, and focus on how Xcode manages it.
GIT Demo Overview (GIT Demo Overview)
Unlike the demo app in other tutorials, this time we will not implement an app to demonstrate a certain iOS SDK feature, and we will not generate a sample product. In fact, we will create a demo project, write several lines of code, and then use this project to demonstrate the version management function provided by Xcode. In other words, we will focus on the IDE, not the iOS itself.
I suggest you follow me to implement this instance project step by step and manually add code in the corresponding place. Don't worry, the amount of code is not large. Following the steps in the tutorial, we will perform multiple version control-related operations, and we must see the results in real time. If I only provide an application with all the operations, you cannot understand these changes.
Let's take a closer look at the key points of Version Control Using Xcode.
Create a Git source (Creating a Git repository)
Every time you create a new project in Xcode, the developer will be prompted to determine whether to use the project as a local git source. In the last step of Project Creation, Xcode has a check box. If you select it, the git source will be added to the project directory. This option is often ignored or considered another useless function of Xcode, especially for developers who have never used git or new programmers.
Open Xcode and create a new project. Select "Application" in iOS, and select "Single View Application" on the Application template page ".
Select next and enter GitDemo in the project name. Make sure that you select iPhone in the following Devices menu. No iPad or universal app is required.
Click Next, that is, the last step. First select a directory for the project to be maintained, and then select Create git repository on (My Mac) at the bottom of the window ):
By default, this option is selected. If you do not want to use git, you can cancel it, but I do not recommend this. In this tutorial, you need to check it and then click the create button.
After the project is created, open the Finder and find the directory of the project. There is a. git subdirectory in the directory. Xcode automatically creates the directory for storing git source data.
If you cannot see the. git directory, you need to make the hidden files visible. Open a Terminal window and enter the following command:
For the OS X Mavericks 10.9:
defaults write com.apple.finder AppleShowAllFiles TRUE
For previous OS X versions,
efaults write com.apple.Finder AppleShowAllFiles TRUE
To restart the Finder application, enter
killall Finder
This is where the project is saved in the local git source. In fact, if you select the appropriate options, this directory will be created. Correspondingly, the. git subdirectory is also created when you create a new application.
Obviously, using Xcode to create a git source is effortless. However, what if you want to add this feature after creating a project without creating a git source? Well, you can create a source for your project at any time, but not using Xcode. Although this rarely happens, I will tell you how to do it.
If you want to, you can directly jump to the next part of this tutorial. I suggest you continue to read it, because the following information is still useful.
Before demonstration, you need to download Command Line Tools through Xcode, because we need to operate under Terminal and some additional Tools. If you have not downloaded the file, go to Xcode> Preferences... Select the Download tab, expand the Components area, and click the Download button on the Right of Commond Line Tools. After the download is complete, a check mark replaces the Download button.
Now, create another project for this example. You can delete it after you finish. Cancel the option for creating the git source at the time of creation. This time we don't want Xcode to prepare a source for us. Name this project NoGitExample and save it to the desktop. Then you can enter the same name as the command I entered next.
After everything is ready, open the Terminal window (if you open one before, close it and restart it to make the installed command line tool take effect ). Switch to the directory of the new project as follows:
cd /Users/YOUR-USERNAME/Desktop/NoGitExample
Do not forget to set the Mac user name in the above command. Next, enter:
git init
This will Initialize an empty source. If you view it in the Finder or enter the ls command, you will see that the. git subdirectory has been created, which is good. Then enter:
git add .
In this way, all contents in the current directory are added to the source. Finally, enter the following command:
git commit -m 'Initial commit'
Next, a change list is displayed for the local git source, as shown in:
Now the git Source is built, but if you go back to Xcode and open the Source Control menu, you will find that everything is still disabled.
This is because Xcode was not notified when we used the command line tool to create a git source. Next, click Xcode> Quit Xcode and restart it. In the NoGitExample project, if you open the Source Control menu again, you will find that all options have been enabled, just as if you checked to create a git Source at the beginning.
Now that the project's mission is over, you can delete it on the desktop.
Now you know how to add a git source for all your projects. Even if you didn't add it at the time of creation, you can manually add the source for it at any time in the future.
Commit Changes (Committing Changes)
Submitting changes refers to storing a new version that contains all changes. In general, when we do some meaningful work and the project is in a stable state, we can submit a change. However, when to submit changes is not required. My suggestion is: after the last change is submitted, if you are afraid that it is difficult to restore the new job that takes a lot of time and energy to be deleted by mistake, you need to submit the change.
By default, Xcode submits a change at the beginning of Project Creation to save the initial state of the project. This work will be completed in the background without interrupting you or asking you to confirm. If you did not add a git source when creating a project, but you manually added it later, you can submit it using the command we used earlier: git commit-m'initial commit'
In fact, if you go to Source Control> History... Menu, you will see the record of the change submitted for the first time, each time you submit the change, there will be a record here.
Next, let's slightly modify our project. In the ViewController. m file, add the following attribute declaration:
@interface ViewController () @property (nonatomic) int sum; @end
Next, modify the viewDidLoad method as follows:
123456789101112 |
- (void)didReceiveMemoryWarning { [ super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. int a = 5; int b = 10; self.sum = a + b; NSLog( "The result is: %d" , self.sum); } |
Take a look at the Project navigator panel. You will find that an m letter is added next to the ViewController. M file, as shown below:
This means that the file has been modified. The file has changed compared to the previous change. In general, this M letter will appear every time you change the file, reminding you of uncommitted changes.
Next let's take a look at how to submit the changes, which is actually very simple. You just need to open the Source Control> Commit menu, and the following window will appear:
Let's take a step-by-step look at what it tells us. On the left side (area marked with 1), all changed files are listed. In this example, only the ViewController. m file is changed, so it is only displayed in the list. If you observe carefully, you will find a selection box on the left of the file, which is selected by default. If you cancel it, the changes to this file will not be submitted.
In the middle area of the window, there are two preview windows. The one on the left is the current version of the file, and the one on the right is the version of the file that was last submitted for change. Because we only submitted a change at the time of creation, the initial state of the file is displayed on the right.
In the blue area of the Left window, the changed content is marked, so that we can clearly see all the changes. If you take a closer look, you will find that there is a small label with numbers between the two windows. These numbers represent changes one by one. By default, there is a small check box next to the number, indicating that the change will be submitted. If you click the small arrow on the right, an option menu will pop up, you can choose not to submit this change or ignore it.
If you select the Don't Commit option, the check box will be replaced by a stop sign, and the change will not be saved to the source.
If you select the Discard Change option, a confirmation window is displayed, prompting that your changes will be restored and you cannot cancel the operation.
If you click the OK button, the changes in the selected area will disappear, just as they have never appeared.
If you carefully observe the preceding commit window, you will see that all your modifications will be changed by Xcode, even if it is a blank line. In fact, a blank line is equivalent to a carriage return, which is invisible on the screen. Therefore, it is a natural change.
In this example, you do not need to ignore any changes, but are allowed to submit all the changes. Therefore, all the changes must be appended with a small check mark.
There is a blank area under the two windows, and the information for submitting changes is displayed in the middle. You can add some brief descriptions about this change. Click it and add the following content:
It is very useful to write meaningful submission information, especially when you submit it frequently. Therefore, consider it as a necessary step.
Now the basic information in this window is almost displayed. It is our first time to submit the window. In the lower right corner of the window, there is a button that says: Commit 1 file.
This button displays the total number of files to be submitted. Click it and your first submission is complete! Open Source control> History and you will find it displayed in the list.
We can see that the information we wrote and the number of changed files are displayed. When Xcode executes the initial submission, all files will be submitted. This time, only the file we modified will be submitted.
In addition, close the history window and check the Project Navigator. You will find that the m Symbol next to ViewController. M has disappeared.
Now, let's prepare for the next submission. This time, we add some new files to the project. The best way to add a file is to create a new class. Therefore, press Command + N to add an Objective-C class. Let this class inherit the NSObject class, named TestClass, and then added to the project.
After that, pay attention to the Project Navigator. You will find that there is A letter id next to the two new class files, which means these files have been added to the Project. Of course, they are not submitted yet.
Open ViewController. h file and import our new class:
#import "TestClass.h"
Next, open the ViewController. m file and declare a private property as follows:
@interface ViewController () @property (nonatomic) int sum; @property (nonatomic, strong) TestClass *testClass; @end
Take a look at the project navigation bar. Four files are to be submitted this time. Let's open the Source Control> Commit menu and submit them.
A total of five files need to be submitted. In addition to the four previously modified items, there is also a project configuration file. Xcode automatically modifies the file after the new class is added to the project. If you open the file TestClass. h or TestClass. m, the window on the left is not displayed, as shown in.
This is because this File has not been submitted before, so there is no comparable version, and only File was added is displayed on the right.
Write a description in the message area: TestClass was added to project .. then click the Commit 5 files button.
In this way, the second manual submission is successful. You can go to the Source Control> History menu to view submitted records.
Comparison between Versions (Comparing Versions)
After you submit different versions of the same project, it is very convenient to track and modify the information between them. When the newly added code cannot run, it is very important to compare it with the previous stable version. You can see what changes have been made to the new version.
To compare the two versions of the same file, you can use View> Version Editor> Show version editor, or click the Version Editor button on the toolbar:
The editor is divided into two columns. At first, the two columns show the same content. Click the small clock icon under the editor to select a version that has been submitted for comparison.
After you click it, the differences between the two versions will be displayed in the editor. Normally, the current version is displayed on the left, and the previous version is displayed on the right. The highlighted blue area shows the changed code, so it is easier to compare the code changes. Continue to select any previous version and observe the differences between the two columns.
You may notice that there are also small labels in the commit window between the two editors. Click the down button to skip the changed options. If you click Ignore Changes, Xcode prompts you if you agree. If you agree to ignore the code, the ignored code will disappear forever and cannot be retrieved. Do not ignore any code.
In addition to the method mentioned above, there is also a way to return to the previous version. If you carefully observe the tool bar under the two editors, there is an arrow clock icon in the middle:
After you click it, the column content between the two panels changes to a series of timestamps that indicate the previous changes. Note that not all of them indicate actual submission. The number of rounded rectangle representing previous versions depends on the number of submissions. In this example, only two such images represent two submissions.
There are two arrows under this column. The panel on the left belongs to the panel on the left, and the arrow on the right belongs to the Panel on the right. Move the arrow to any previous version and you will see the changes in the corresponding panel. If you want to compare the differences between the current version and any previous version, point an arrow to the local line and move the second arrow. The timestamp from the bottom to the top represents the code from the new to the old. On the base line, you will see the content submitted last time. Move up and you will see the initial submission, as shown in:
Now you know how to compare the differences between versions. Before continuing to dive deeper, let's take a look at the exercises we have learned.
Who is wrong? (Who's Got the Blame)
In addition to comparing the file version, Xcode also allows you to track the file submitter and who changed the code. This is useful in a multi-person team. To use this function, click the View> Version Editor> Show Blame View menu. Or move the mouse over the Version editor button on the toolbar and select the Blame option. A window similar to the above will appear:
As you can see, the current file is divided into several segments based on different commits, the author of each code segment, and the submitted information and other information are displayed in a special panel on the right of the window.
If you have not done so, open the blame view by yourself. Pay attention to the way in which Xcode displays the code snippet author. In this view, you can easily find out when a code is submitted and other information you want. Place the cursor over the blame panel and some other modified information will be displayed. When the pointer stops at the submission segment, a small button with an image will appear on its right. Click the selected code section to bring up an additional submission information window. In this window, you can also jump to the comparison window (indication #1) and specific submitted modification files (indication #2 ).
In addition to comparing views and blame attempts, there is actually a Log view ). You can open it through View> Version Editor> Show Log View. Or if you do not describe it here. You can check it on your own. After all, it is not that complicated to use.
Branches)
Imagine that your current project has a version to be released or already released, and you suddenly want to add some new features, how can we prevent the newly added code from paralyzing the entire project? The answer is simple: you need to use the branch.
How can we simply understand the branch? You can think of your project as a tree. Stable version is the backbone of the tree. Any version that adds new features must be part of the trunk. Branches, like the branches of a tree, grow from the trunk to different directions. In git, you can create branches to set a new path for your code to implement new features without worrying about cracking the trunk in development.
In fact, by default, git has a branch called master. The first submission of Xcode Automatic Execution occurs in this branch. Generally, individual developers only develop in the master branch, which is not a good habit. Whether you are single-handedly or in group cooperation, I think it is very important to use the branch when making major changes to the project or adding major features. It will avoid a lot of trouble for you. Of course, in a team project, it is almost necessary to build a branch for the code you are responsible.
Note the following two points about the branch:
The final product submitted to App Store or customer must be a master branch project in the project.
Any code or functions implemented in the second branch must be eventually merged into the master branch, so that the officially released application is complete. (I will talk about this later)
When you start a new branch, you actually start from the current working status, even if you have any uncommitted changes. From this time on, all changes will only be reflected in the branch.
Now let's go back to Xcode. To create a branch, click Source Control> GitDemo-master> New Brance... The following menu is displayed:
Let me name this branch AnotherBranch. It doesn't matter how you name it. Click OK. The new branch will be created and the current code will be copied to the new branch.
Open the Source Control menu, and you can easily find out which branch of the activity is: it is next to the project name.
Now, let's make a new branch commit. Before that, let's add some new code. Open the class file and add the following method declaration in the private property area:
@interface ViewController () ...-(void)sayHello; @end
Then implement it:
123 |
-(void)sayHello{ NSLog( "Hello" ); } |
Finally, call it in viewDidLoad:
123456 |
- (void)didReceiveMemoryWarning { ... [self sayHello]; } |
Now, click the Source Control> Commit menu, and the version comparison window will display. You will see only one modified file, ViewController. m. The newly added file will be highlighted.
Enter the next submission information: First commit to a new branch, and then click commit 1 file. Now the change to the AnotherBrance branch will be submitted.
Open the Version Editor (menu View> Version Editor> Show Version Editor) and find the toolbar under the editing panel on the right. You will see that the selected branch is AnotherBranch. Click it, you will see that this branch and the master branch appear at the same time. If you select any version from the master branch, Xcode will highlight the difference between the two. In this way, you can easily track code changes between all branches.
Finally, Switch to another Branch or master Branch. You can click Source Control> GitDemo-AnotherBranch> Switch to Branch... Menu.
From this window, you can select the branch you want to jump to. Here let's jump back to the master Branch:
Select it and click the Switch button. The master branch will become the active branch of course. You will find that the changes made in AnotherBranch do not appear in the master branch. Good. We have not modified the stable version while managing the project.
Merge Branch)
It is a good habit to develop in the branch. However, if the code changes need to be reflected in the release version, the branch must be merged into the master branch. This section will show you how to merge them. In Xcode, it is very easy to merge two branches into one.
Let's make a small experiment to see how merge works. First, make sure that the master branch is the current active branch. If not, change it To Source Control> GitDemo-AnotherBranch> Switch To Branch... Menu, and select the master branch from the display window.
Next, create a New Branch: Source Control> GitDemo-master> New Branch... Menu, named LastBranch
First let Xcode fly a meeting, then, go to the ViewController. m file, and then create a private method, first declare it:
@interface ViewController () ... -(void)sayByeBye; @end
Then implement it:
123 |
-(void)sayByeBye{ NSLog( "Bye - Bye" ); } |
Finally, call it in the ViewDidLoad method:
123456 |
- (void)viewDidLoad { ... [self sayByeBye]; } |
Before merging, submit these changes. Use the Source Control> Commit menu to submit the job.
At this point, you have two options for merging two different branches:
Merge from Branch: Any changes related to the branch you select will be merged into the current active branch.
Merge to branch: any changes to the current active branch will be merged to the branch you select.
You can find these two methods in the Source Control> GitDemo menu. Note that when your active branch is a master branch, the second option is not optional.
Suppose a developer implements a sayHello method in the Anotherbranch branch, and another developer creates and implements the sayByeBye method in LastBranch. Now you need to merge the work of two people into the next stable version, think about what you need to do? Very simple: Merge the changes from the two branches as follows:
First, make sure that the current active branch is the master branch.
Then, open Source Control> GitDemo-master> Merge From Branch... Menu, select AnotherBranch, and click the Merge button.
Next, a comparison window will appear, in which you will see the changes to the Merged Code. Let's take a look, and then click the Merge button.
Xcode will ask if you want to save the project snapshot and click Enable. Let Xcode fly for a while, and that's fine. The content added in AnotherBranch has been merged into the master branch.
Use the same method to merge LastBranch. You will find that if you do not submit changes, Xcode will not let you merge again. So we have to submit it first. In the comparison window, you will find that a red area shows the changes after merging, instead of the previous blue. This means that the code in the branch will replace the code in the original active branch.
You can easily avoid this phenomenon. There are several small buttons Under the editing panel. You can try to see what they all do. I chose the first one, which means that the code of the master branch will be placed on it, the Code of another branch will follow it.
Process all the code to be changed. Do not omit it. Click the Merge button.
Congratulations! You have successfully learned to merge code from multiple branches. in a similar situation, you should also.
Discarding Changes)
It is very useful to discard unwanted code changes. Just a little bit, the changes since the last commit will be abandoned. This feature comes in handy when you try to start from the last stable state during the development process. Note that there is no way to change this function. You cannot cancel this operation after you click it. Therefore, be careful when using this function!
Previously, when we were discussing version comparison, we learned how to ignore some of the changes. Next we will learn how to ignore all the changes since the last commit.
To test this function, first write some code to open ViewController. h and add a public method declaration:
12345 |
@interface ViewController : UIViewController -(void)aVeryCoolMethod; @end |
Now, let's add an implementation of this method in ViewController. m. Simply:
123 |
-(void)aVeryCoolMethod{ NSLog( "I'm feeling that you'll discard me... Really?" ); } |
If you notice that the Project Navigator has a M id next to the file we just changed, it is good to see if the files will return to the status before the change if you ignore these changes.
Here is an important detail: You can choose to ignore the changes to all files, or you can choose to ignore the changes to a single file, depending on you. If you want to ignore the changes to a file, select the file first. In this example, if you select only the ViewController. m file and open the Source Control menu, you will find the Didcard Changes option in ViewController. m. Similarly, if you only select ViewController. h. However, if you want to ignore the changes to these two files (assuming there are more than two changes here), select them in the Project Navigator and then open the Source Control menu. The corresponding location displays Discard Changes in 2 Files, as shown below:
However, we will not use this button this time. We will use Discard All Changes. After you click it, a confirmation box will appear. This is the only way for Xcode to prevent accidental code deletion.
Click Discard All Changes. Then the public method you just wrote will always be in the past. As you can see, you only need a few steps to restore the current working status to the previous submission, so I will remind you again to focus on using Source Control, click this button.
Summary
Through this tutorial, I tried my best to elaborate on how to implement Version Control in Xcode. What actually works behind the scenes is git, the most widely used version control system on the earth. You may have noticed that I didn't mention GitHub or any Xcode features much in the tutorial-I did it on purpose. I want to focus on using Xcode for git management. GitHub can be used only when you know how to implement version control. I would like to reiterate that if you are working as a team, using version control tools is required! If you are dedicated, it is also necessary to use a version control tool, which can protect your work by spending a lot of time and energy, in addition, you can simply scale up new features. As some people have said, this tool will never be returned once it is used! Finally, I hope this tutorial will be useful to you.