Turn-----Use git for source version control in Xcode

Source: Internet
Author: User
Tags how to use git using git version control system

Use git for source version control in Xcode
    • Http://www.cocoachina.com/ios/20140524/8536.html

This document is translated from understanding Git Source Control in Xcode (translator Myshire) and you are welcome to join our translation team.

In the application development process, a very important part of the work is how to source version control. When there is a problem with the code, we need to restore the code to the original normal version. If more than one person develops a project together, the control of the code can be very complex. Fortunately, developers do not have to control these themselves, because there is specialized software to be responsible for, called version control System.


The version control system, or the modification of the control system, is actually a way to detect changes in the source file and save it for later reference using the mechanism (software). It can also record other useful information, such as which developer modified the code, when it was modified, which part was modified, and other historical information. The version control system can compare different versions of the code and, if necessary, restore the entire project to a previous version, tracing harmful code and thereby reducing product errors.

With a version control system, developers can work on different branches of a project, and when the various parts of the project are fully developed, they are put together to form the final version, a process known as merging. In fact, this practice is quite common in teams and software companies: everyone is responsible for part of the project, and ultimately all parts are integrated into the final product.

The version control system is not required for individual developers, but we strongly recommend that developers use it because it allows the code to be easily converted between the wrong version and the version that can work. In fact, many developers never use a similar tool, they will save the original project manually when the project adds new features. This is actually a bad habit, because version control software can do this task better and more efficiently.

Git is a common version control system that was first developed by Liunx's father, Linus Torvalds, and that Git uses virtual directories, also known as repositories, to manage everything. Git can be called from the command line, and there are desktop applications designed specifically for it. If Git is unfamiliar to you, I suggest you check out some of its information online. The deeper content of git is beyond the scope of this article.

Some new features using git have been introduced from XCODE5. It consolidates the functions of Git into a single menu and provides submenus to control the merging of software. In the next reading you will find that using Git for versioning is fairly straightforward and quick.

Our next task is to learn how to use git in Xcode and how Xcode integrates the features of Git. If you feel that you are unfamiliar with these, I suggest you go online to search for relevant content. In the next tutorial, I'll assume you already know what version control system and Git are, and focus on how Xcode manages it.


Git demo overview (Git demo overview)

Unlike the demo app in other tutorials, this time we're not going to implement an app to demonstrate an iOS SDK feature, and eventually we won't have a sample product. In fact, we'll create a new demo project, write a few lines of code, and then use this project to demonstrate the version management capabilities that Xcode provides. In other words, we'll focus on the IDE instead of iOS itself.

I suggest you follow me step-by-step implementation of this instance project, manually add code in the appropriate place, do not worry, the amount of code is not many. Following the tutorial steps, we will perform a number of repetitive versioning-related operations, and we must see the results in real time. If I only provided an application with all the operations, you wouldn't be able to appreciate the changes.

Okay, nonsense, let's take a closer look at the main points of version control with Xcode.

Create a git source (Creating a git repository)

Each time a new project is created in Xcode, the developer is prompted whether to use the project as a local git source. In the final step of creating the project, Xcode will have a check box, and if it is selected, the Git source will be added to the project directory. This option is often overlooked, or is considered another useless feature of Xcode, especially for developers who have never used git, or who are novice programmers.

Open Xcode and create a new project. Select "Application" in the iOS area and select "Single View Application" on the app template page.

Choose Next, enter Gitdemo in the project name, make sure the Devices menu below selects iphone, no ipad or Universal app.

Click Next, which is the last step, select a directory to keep the project in place, then choose Create Git repository on (My Mac) at the bottom of the window:

By default, this option is selected, and if you don't want to use Git, you can cancel it, but I don't recommend it. In this tutorial, you need to tick it up and click the Create button.

After the project is created, open the Finder, locate the directory where the project is stored, and in the directory, there is a. Git subdirectory, and Xcode is automatically created for storing git source-related data.

If you don't see the. git directory, you need to make the hidden files visible. This is done by opening a terminal window and entering the following command:


For OS X Mavericks 10.9:

    1. Defaults write Com.apple.finder appleshowallfiles TRUE

For previous versions of OS X,

    1. Efaults Write Com.apple.Finder appleshowallfiles TRUE

In order to restart the Finder app, enter

    1. Killall Finder

This is where the project is saved in the local Git source. In fact, if you choose the appropriate option, the directory will be created. Accordingly, when you create a new app, the. Git subdirectory is created together.

Obviously creating a git source with Xcode is effortless, but what if you didn't create a git source when the project was created, and then you want to add this functionality? Well, you can actually create a source for your project at any time, but not with Xcode. I'll tell you what to do, even though this happens very rarely.

If you want, you can skip to the next part of the tutorial. I suggest you keep reading it, because the information is useful.

Before making a presentation, you need to first download command line tools through Xcode, because we are going to operate under terminal and need some extra tools. If you haven't downloaded it, go to xcode>preferences ... menu, select the Download tab, expand the Components section, and click the Commond line tools right download button. Once the download is complete, a checkmark will replace the download button.


Now, to create a project for this example, you can delete it after it's done. Cancels the option to create a git source when it is created. This time we don't want Xcode to prepare a source for us. Name the project Nogitexample, save it to the desktop, and then you can follow the same command that I entered.

When you're ready, open the terminal window (if you've opened one before, turn it off and then restart, so that the command-line tool we installed takes effect). Switch to the directory for the new project below:

    1. Cd/users/your-username/desktop/nogitexample

Don't forget to set your Mac's username in the command above, and then enter:

    1. Git init

This initializes an empty source, and if you view or enter the LS command in the Finder, you will see that the. Git subdirectory has been created, well, and then enter:

    1. git Add.

In this way, all the contents of the current directory are added to the source, and finally, enter the following command:

    1. git commit-m ' Initial commit '

A list of changes performed by a local Git source appears, as shown in the following:

Now the git source is built, but if you go back to Xcode and open the Source Control menu, you'll find that everything is still disabled.

This is because when we use the command-line tool to create a git source, Xcode is not notified, click Xcode>quit Xcode below, and then restart it, in the Nogitexample project, if you open the source Control menu again, You'll find that all the options have been enabled, just like the first tick to create a git source.

Now that the mission of this project is over, you can delete it on the desktop.


Now that you know how to add a git source for all your projects, you can add it manually at any later time, even if you didn't add it when you created it.

Commit changes (committing changes)
Commit changes refer to storing a new version that contains all the changes. In general, when we do some meaningful work and the project is in a stable state, we can submit a change. However, there are no hard rules as to when to submit changes. My advice: After the last commit change, if you're afraid that a new job that takes a lot of time and effort to get deleted is hard to recover, you'll need to commit the changes.

By default, Xcode submits a change to the project creation early, in order to save the project's initial state. This work will be done in the background, will not disturb you or ask you to confirm. If you did not add a git source while the project was created, but then you manually added it, you can commit it through the commands we used earlier: Git commit-m ' Initial commit '


In fact, if you go to source control>history ... menu, you'll see a record of the initial commit change, and each time you commit the change, it will be recorded here.

Next, let's change our project slightly, and in the Viewcontroller.m file, add the following attribute declarations:

    1. @Interface Viewcontroller ()
    2. @property (nonatomic) int sum;
    3. @end

Next, modify the Viewdidload method as follows:

    1. -  (void) didreceivememorywarning  
    2.     [super  Didreceivememorywarning];  
    3.     // dispose of any  Resources that can be recreated.  
    4.  
    5.     int a  = 5;  
    6.     int b = 10;  
    7.  
    8.     self.sum = a + b;  
    9.  
    10.     nslog ( "The result  is: %d ",  self.sum);  
    11. }  

Take a look at the Project Navigator panel and you'll find an M-letter added next to the viewcontroller.m file, like this:

This means that the file has been modified, and the file has changed compared to the last commit change. In general, every time you change a file, the M-letter will appear, reminding you that you have uncommitted changes.

Here's a look at how to commit changes, which is very simple, just 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 (the area labeled 1), all the changed files are listed, in this case only viewcontroller.m this file is changed, so only it is displayed in the list. If you look closely, you will find a selection box to the left of the file, which is selected by default, and if you cancel it, the file changes will not be submitted.

In the middle of the window, there are two preview windows, the one on the left is the current version of the file, and the right is the version of the file's last commit change. Because we are only making one change at the time of creation, so the right side shows the initial state of the file.


The blue area of the left window is marked with the changed content, so that we can clearly see all the changes. If you look closely, you will find a small label with a number between the two windows, which represents each change. Next to the number, by default there is a small tick indicating that this change will be submitted, and if you click on the small arrow on the right, a menu of options will pop up and you can choose not to commit the change or ignore it.


If you select the Do not commit option, the small tick is replaced by a stop flag, and the change is not saved to the source.

If you choose the Discard change option, a confirmation window pops up, prompting you to make the changes that will be restored and cannot cancel the operation.

If you click the OK button, the changes in the selected area will disappear as if they had never been seen before.

If you look closely at the submission window above, you will see that all of the changes you have made 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, so it is a matter of course to change.

In this example, you do not have to ignore any changes, but instead allow all of the change to be committed, so all the change tags must be a small checkmark next to them.

Below the two Windows is a blank area with information about the commit changes in the middle. This place can add a brief description of the change, click on it and add the following:

It is useful to write meaningful submissions, especially when you are submitting frequently. So take it as a necessary step.

Now the basic information of this window looks almost, it is time to do our first submission. At the bottom right of the window, there is a button that says: Commit 1 file.

This button displays the total number of files that need to be submitted. Click on it and your first commit is complete! Open Source Control > History and you will find it will be displayed in the list.

As you can see, the information we write and the number of files that are changed are displayed. Xcode executes the initial commit and all the files are submitted, and this time only the file that we modified is submitted.


Also, close the History window and look at Project Navigator, and you'll find that the M symbol next to VIEWCONTROLLER.M has disappeared.


Now, let's prepare for the next commit. This time, we add some new files to the project. The best way to add a file is to create a new class, so press the COMMAND+N key combination to add a objective-c class. Let this class inherit the NSObject class, take the name TestClass, and add it to the project.


When you're done, take note of Project Navigator, and you'll find that two new class files have an alpha identifier next to them, which means the files have been added to the project and, of course, they haven't been submitted yet.


Open the ViewController.h file and import our new class:

    1. #import "TestClass.h"

Next, open the VIEWCONTROLLER.M file and declare a private property as follows:

    1. @Interface Viewcontroller ()
    2. @property (nonatomic) int sum;
    3. @property (nonatomic, strong) TestClass *testclass;
    4. @end

Take a look at the project navigation bar, this time there are four files to be submitted. Let's open the source Control > Commit menu and submit them.

A total of 5 documents are required to be submitted. In addition to the previous four modifications, there is a project configuration file. Xcode automatically modifies this file after the new class is added to the project. If you open the TestClass.h or testclass.m file, the left window does not appear any more, as shown in.

This is because there are no previously committed records in this file, so there is no comparable version, and only file was added is shown on the right.


Write a description in the message area: TestClass was added to project. Then click on the Commit 5 files button.


This is the second time that manual submission succeeds. You can view the submitted records in the source Control > History menu.

Comparison between versions (comparing Versions)
After you have submitted different versions of the same project, it is very convenient to track the changes as you compare them. When the newly added code does not run, it is important to compare it with the version, and you can see what changes have been made to the new version compared to the last stable version.

To compare two versions of the same file, you can use view>version editor>show version editor, or click the Version Editor button on the toolbar:

Once clicked, the editor is divided into two columns. Initially, the two columns will show the same content, click on the Small clock icon below the editor, you can select the previously submitted version for comparison.

After clicking, the difference between the two versions is displayed in the editor. Typically, the current version of the file is displayed on the left, and the previous version is displayed on the right. The blue highlighted area shows the changed code, so it's easy to compare the changes in the code. Continue to select any previous version and observe the difference between the two columns.

You might notice that in the middle of two editors, there are small tags that you see in the submission window. Click the down button to jump out of the options that let you ignore the changes. If you click Ignore changes, Xcode will prompt you if you agree. If you agree to ignore them, the ignored code will disappear forever and cannot be found again. So be careful not to inadvertently ignore any code.

In addition to the methods mentioned above, there is a way you go back to the previous version. If you look closely at the toolbar below the two editor, there is a clock icon with an arrow in the middle:

After clicking on it, the contents of the columns between the two panels change to a series of timestamps that represent the previous changes. Note that not all of them represent actual submissions. The number of rounded rectangles that represent the previous version depends on the number of commits. In this example, only two of these graphs represent two commits.

Below this column, there are two arrows. The left side of the panel belongs to the left, and the right arrow belongs to the right panel. Move the arrows to any previous version and you'll see the changes in the corresponding panel. If you want to compare the difference between the current version and any previous version, let an arrow point to the local row, and then move the second arrow. The timestamp from the bottom to the top represents the new to the old code. On the base line, you will see the content of the last commit. Continue moving up and you will see the initial commit as shown in:

Now you know how to compare the differences between versions. Before you go any further, take a look at the exercises you have learned in front of you.


Whose fault is it? (who ' s Got the Blame)
In addition to comparing versions of files, Xcode allows you to track the submitter of a file and who changed which part of the code. This is very useful in a multi-person team. To use this feature, click View > Version Editor > Show Blame View menu. Or, put the mouse on the version Editor button on the toolbar and select the blame option. A window similar to the one above will appear:

As you can see, the current file is divided into sections by horizontal lines based on different submissions, the author of each code snippet, and the submission information and other information are displayed in a special panel on the right side of the window.

If you haven't done it, do it yourself. Open the blame view and notice how Xcode shows the author of the snippet. In this view, it is easy to find out when a code is submitted by whom and the other information you want. Placing the mouse on the blame panel will display some additional information about the changes. When the pointer pauses over the submission segment, a small button with a picture appears to the right of it. Click to select the code, and an accompanying submission window will pop up. In this window, you can also jump to the diff window (indication #1), as well as a specific commit modification file (indication #2).


In addition to comparing views and blame, there is actually a log view. You can open it from View > Version Editor > Show Log view. Or if you're here, you're not going to say it in detail. You can take a look at it yourself, after all, it's not so complicated to use.


Branch (Branches)
Imagine that your project now has an upcoming release, or a version that has been released, and you suddenly want to add some new features, how to prevent these newly added code from paralyzed the entire project? The answer is simple: you need to use a branch.


How to understand the branch simply? You can think of your project as a tree, and the 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 and grow in different directions. In Git, you can create a new path for your code by creating a branch to implement the new feature without worrying about breaking the trunk in development.

In fact, there is a branch in git, called Master, by default. The first commit that Xcode performs automatically occurs in this branch. Usually, a separate developer only develops in the Master branch, which is not a good habit. Whether you're working alone or in a group, I think it's important to use a branch when you make a major change to a project or add significant functionality, and it will save you a lot of trouble. Of course, in a team project, it is almost necessary to make a branch of the code that is responsible for your own part.

On the branch, you must remember the following two points:
1. The final product submitted to the App store or customer must be the master branch project in the project.
2. Any code or functionality implemented in the second branch must eventually be merged into the master branch, so that the officially released application is complete. (I'll talk about this later)

When you start a new branch, you are actually starting with your current working state, even if you have any uncommitted changes. From this time on, all changes will only be reflected in the branches.

Now let's go back to Xcode, to create a branch, click Source Control > Gitdemo-master > New brance ... This menu will then pop up the following menu:

A name for this branch, I'll call it anotherbranch. It doesn't really matter how you name it now. Click the OK button, wait for the new branch to 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 of the active branches is: it's next to the project name.

Now, let's do 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:

    1. @Interface Viewcontroller ()
    2. ...
    3. -(void) SayHello;
    4. @end

Then implement it:

    1. -(void) sayhello{
    2. NSLog ("Hello");
    3. }

Finally, it is called in Viewdidload:

    1. -(void) didreceivememorywarning
    2. {
    3. ...
    4. [Self SayHello];
    5. }

Now, click on the source Control > Commit menu, the version Comparison window will appear, you will see only a modified file--viewcontroller.m file, the newly added section will be highlighted.


Enter the next commit message: First commit to a new branch, then click the Commit 1 File button. Now the Anotherbrance branch changes will be submitted.

Open Version Editor (menu View > Version editor > Show Version Editor), find the toolbar below the edit panel on the right, and you will see that the selected branch is Anotherbranch, click it, You'll see this branch and the master branch appear at the same time, choose any version from the Master branch, and Xcode will highlight the difference between the two. This allows you to easily track changes in code across all branches.

Finally, switch to another branch, or the master branch, and you can click on source Control > Gitdemo–anotherbranch > Switch to Branch ... Menu.

From this window you can select the branch that you want to jump from, and here let's jump back to the master branch:

Select it and click the Switch button, and the Master Branch will become an active branch of course. You will find that the changes made in Anotherbranch do not appear in the master branch. Well, we did not revise the stable version while managing the project.

Merge branch (merging Branches)
It is a good practice to develop in a branch, however, if the code changes are to be reflected in the release, then the branch must be merged into the master branch. In this section we will show you how to merge them. In Xcode, merging two branches into one is very simple.


Let's do a little experiment to see how the merger works. First, make sure that the Master branch is the active branch now. If not, change it quickly: Source Control > Gitdemo–anotherbranch > Switch to Branch ... menu and select Master Branch from the display window.

Next, create a new branch: Source Control > Gitdemo–master > New Branch ... menu, named Lastbranch

Let Xcode fly for a while, then, to the VIEWCONTROLLER.M file, create a private method that declares it first:

    1. @Interface Viewcontroller ()
    2. ...
    3. -(void) Saybyebye;
    4. @end

Then implement it:

    1. -(void) saybyebye{
    2. NSLog ("Bye-bye");
    3. }

Finally, it is called in the Viewdidload method:

    1. -(void) Viewdidload
    2. {
    3. ...
    4. [Self Saybyebye];
    5. }

Before merging, commit these changes first. Use the source Control > Commit menu to execute the commit.

Finally came this step, about merging two different branches into one, you have two options "
1. Merge from branch: Any changes related to the branch you selected will be merged into the current active branch.
2. Merging to a branch: Any changes to the currently active branch will be merged into the branch of your choice.

Both of these methods can be found in the source Control > Gitdemo menu. Note When your active branch is the master branch, the second option is not selectable.

Suppose a developer implements a SayHello method in the Anotherbranch branch, another developer creates a Saybyebye method in Lastbranch, now you need to merge two people's work into the next stable version and think about what you need to do? Very simply, 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 then click the Merge button.

A comparison window will appear, where you will see the changes to the code after the merge, take a look at it, and then click the Merge button when you feel almost there.

Xcode asks if you want to save a snapshot of your project and click the Enable button. Let Xcode fly for a while, then just fine. The content added inside the anotherbranch has been merged into the master branch.

Use the same method to merge Lastbranch. You'll find that if you don't commit the changes, Xcode won't let you merge again. So we had to submit it first. In the Compare window you will find a red area that 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 the occurrence of this phenomenon. There are a few small buttons underneath the edit panel, you can try them all, I chose the first one, which means that the code of the Master branch is placed on top, and the code of the other branch follows it.

Handle all the next code that needs to be changed, without missing it. When you're finished, click the merge button.


Congratulations to you! You have successfully learned to merge the code from multiple branches, and you should have it in a similar situation.

Ignore changes (discarding changes)
It is useful to discard unwanted code changes, just a little bit, since the changes after the last commit are discarded. This feature comes in handy when you find a big mess in the development process and you want to start over from the last stable state. Pay attention to discard changes this function no back, after the point you have no way to undo this operation, so, be careful to use Ah!

Before, when we were discussing version comparisons, we learned how to ignore a certain part of the change, and let's learn how to ignore all changes since the last commit.

To test this functionality, first write some code to open ViewController.h and add a public method declaration:

    1. @Interface Viewcontroller:uiviewcontroller
    2. -(void) Averycoolmethod;
    3. @end

Now, let's add an implementation of this method to the VIEWCONTROLLER.M, and simply click on the line:

    1. -(void) averycoolmethod{
    2. NSLog ("I ' m feeling that's you ll discard me ... Really? ");
    3. }

If you notice project Navigator, we've just changed the file with an M-id next to it, very well, we'd like to see if these changes are ignored, whether they go back to the state before the change.

Here's an important detail: you can choose to ignore all the file changes, or you can choose to ignore the individual file changes, which is entirely up to you. If you want to ignore changes to a file, first select the file. In this example, if you select only the viewcontroller.m file and then open the Source Control menu, you will find Didcard changes this option in the VIEWCONTROLLER.M. Similarly, if you only choose ViewController.h is also a reason. However, if you want to ignore the changes to these two files (assuming there are more than two changes), select them in Project Navigator, and then open the source Control menu. The corresponding location will show discard changes in 2 Files, as follows:

However, this time we will not use this button, we will use discard all changes. After clicking on it, a confirmation prompt will appear, which is the only measure that Xcode prevents you from accidentally deleting the code.

Click Discard all changes, and the public method you just wrote will always be in the past. See, it takes just a few steps to get you back to the previous commit, so I'll remind you to be careful with the source Control, and don't delay the button.

Summarize
In this tutorial, I tried to detail how version control is done in Xcode. In fact, behind the scenes, what really works is git----the most applied version control system on Earth. You may have noticed that I did not mention too much about GitHub or any of the features of Xcode in the tutorial----actually I did it on purpose. I want to focus on the content of git management using Xcode. It's only when you know how to version control that you can really use GitHub. I would like to reiterate that if you are a team at work, using version control Tools is a must! If you're in a single fight, it's also necessary to use version control tools, which can guarantee the work you spend a lot of time and effort on, and can be easily extended as you add new features. This tool as some people say, once used, will never go back! Finally, I hope this tutorial will be useful to you.

Go-----Use git for source version control in Xcode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.