Objective-C basic tutorials (7)

Source: Internet
Author: User

Chapter 2: learn more about xcode
Xcode is a useful tool with many powerful functions, but not all functions are easy to find. If you plan to use this powerful tool for a long time, you must know it as much as possible. This chapter describes how to use the xcode Editor, which is helpful for writing and browsing code and searching for information. In addition, some methods for debugging programs using xcode are also mentioned.
Here we will introduce xcode4.3.2, the latest version of this book. Apple is keen to add or delete some things during xcode upgrade. (Silent voice: I am currently using 4.6.2. I don't know how many of them are the same)
Window layout Overview
Toolbar: The top of the bit program window, with many tool buttons on it.
Navigator panel: located on the left of the window. It is usually used to display the file list in the project. You can also browse other content, such as symbol, search, and issue) debug, breakpoints, and logs ). You can hold down the command key and a number key (from 1 to 7) or click the icon at the top of the Panel to switch the view.
Editor panel: Right-middle position. Most of the time you have to show your skills here, write a line of source code, change the world, and fly.
Checker panel: located on the right of the window, displays information related to the context (currently selected content) and buttons for modifying the selected Attribute values.
Debugger panel: center at the bottom. When the debugger is running, the stack and debugger controller will appear here.
Library panel: hidden in the lower right corner of the window, which lists the project resources, objects, code snippets, and other items that may be used.
Change company name
Xcode writes the file name, project name, creator, and creation time in the comment block to let you know at a glance which file you are viewing, who created it and the time it was generated.
It is easy to change the company name. Select a project on the navigator panel and make sure that the project name is selected under the project section of the compiler panel. Observe the checker panel on the right and you will see the Organization text box in the Project Document section. Enter your company name.
Tips for using the editor
Xcode provides several basic methods for organizing projects and source code editors. We have introduced the default interface, which is mainly used to manage real-time projects and to execute coding tasks. The editor panel is used to display source files, the content depends on the source file selected in the left-side navigation pane.
Here we will explain in detail what you see in the navigator panel. The file list shows all the useful parts of the project: the source file, the linked framework, and the products folder of the build program. You can also find other utilities, such as Access source code version control, all the project symbols, and smart folders.
After a file is selected, you will see the file path under the toolbar at the top of the window, telling you the position of the file in the project. You can use the search box at the bottom of the navigator panel to filter list files.
The browser lists the source files with the character car in each name. You can select them in the browser so that the editor displays their content. Because large projects may have more than one hundred source files, browsers are a convenient management tool if there are many files. This chapter will introduce topics related to source file navigation.
When writing code, you can hide the browser, so that the available area of the screen will be larger. There is a set of toolbar buttons marked as view in the upper-right corner of the window. There are three buttons, you can hover your mouse over to view their functions, but let's talk about them here: the buttons on the left are used to hide or display the navigator panel, you can also use the command + 0 shortcut to call it. The switch button in the middle is used to check whether the debugger area is visible, and the button on the right is used to check whether the Panel is visible.
It is also useful to use an independent window to display their own source files, especially when you want to compare two different files. Double-click the source file in the navigator panel to open it in a new window. You can also display the same file in two different windows, but note that sometimes the content in these two windows is not synchronized, therefore, you need to click a window to synchronize them.
You may prefer to use labels (as in Safari) instead of multi-window display. Xcode has been expected. It's like xcode users know safari users. To display tags, select View-> show tab bar. To add a tag, click the plus sign on the right of the tag bar.
Write code with xcode help
Many programmers write code day and night. Xcode provides some functions for all programmers to make code writing easier and more interesting.
First line indent
Sometimes, a lot of code editing can make it messy. xcode can improve this situation. After the text is selected, press the control key and click it to view the context menu of the editor. Then, select Structure --> re-indent option, and xcode reorganizes everything. You can use the shortcut key control + I to achieve the same effect.
Press the command + [or command +] key to move the selected code left or right. If you want to adjust the code in xcode according to your own style, see xcode preferences text editing and indentation.
Code automatically completed
Xcode will give suggestions when you enter the code. This is the code prompt function of xcode, usually called Automatic completion of code. During programming, xcode generates an index for all the content, including the variable name and method name in the project and the imported framework. It knows the name and type of the local variable, and may even know whether your encoding style is good or bad. Press the tab key to receive the prompt from xcode. If you want to close the prompt list, Press ESC, and then press ESC to open the automatic Completion list again.
Hover the mouse over the method name. A question mark icon is displayed on the right of the window. Clicking it will open a mini Help window that describes the method information.
Bracket matching
When you enter the program code, you may find that the screen will flash after entering certain characters (such as ")", "]", and. If this happens, xcode is telling you where the parentheses corresponding to the braces are. we enter a right parenthesis at the end of the second line, after completion, the corresponding left parentheses will flash with the background color for a moment.
This feature is sometimes referred to as "Parentheses matching", which can help you end a series of complex separators (that is, parentheses. Make sure that each ending bracket you enter matches the ending bracket you want to close. If you make a mistake, xcode will issue an alert and cannot display matching brackets.
You can also double-click a separator, and xcode will select it and all the code between the matching brackets.
Batch Edit
Sometimes, you may want to apply the similar changes in the Code to several other places, but you do not want to edit them one by one. It is dangerous to manually perform a large number of similar editing operations, because humans are not good at repetitive and boring work. Fortunately, computers are competent for this kind of work.
In this regard, the first xcode function that helps us not to operate code, but to build a security net. Select File> Create snapshot... or press command + Control + S to remember the current state of the project. Now you can edit the source file with ease, you can even "break" your project in various ways as you like. If you realize that you have made a very serious mistake, you can open the snapshot window using the "file" Restore snapshot... option, so that you can use the previous snapshot to restore the project. Create a snapshot before you take any risk.
After that, it will naturally find/Replace (silently speaking: What? Have you ever used search/Replace ?! Okay... I would like to express my sincere silence for your dead brain cells and wasted youth ). The "edit" find "sub-menu contains several very convenient options. Select find In workspace (command + Shift + F), or select the search option in the navigator to search or replace all files in the project.
This search and replacement function is not easy to use. If you only want to rename the variable in the function, it may perform extra operations (for example, changing the variable with the same name elsewhere ). It cannot change the source file name.
Xcode has two functions to make up for these shortcomings. The first feature is called edit all in scope. You can select a symbol, such as a local variable or parameter, and click it to see a downward arrow on the right side, it seems that the cursor points to a local variable or parameter first, and then a dotted box appears for the corresponding variable or parameter. Move the mouse over the dotted box and the downward arrow appears ). Click the arrow to view a menu and select the edit all in scope option. The entered content will update all the places where the symbol appears. After the input is complete, you only need to click somewhere else in the source file editing window and then exit edit.
All in scope mode.
Xcode has some built-in refactoring tools, one of which allows you to easily rename classes. It can not only rename the class, but also do some nice work, such as renaming the corresponding source file. In addition, if you develop a GUI program, it can also go deep into the NIB file for modification operations (speak silently: do not understand? It is said that the subsequent chapters will continue to be introduced. Please be patient ).
Let's replace all the car class names with the automobile class. Open the car. h file in the editor and place the cursor in the class name car. Select Edit refactor rename... to display a small dialog box, enter the class name in it, and click the preview button. xcode will display the task to be executed. It lists all files that may be modified and their changes.
After confirming that these changes are correct, click the Save button. If this is the first reconstruction, xcode will ask if you want to enable automatic snapshot backup. It is a wise decision to select enable. In this way, xcode will create a snapshot for you before every reconstruction. Although it will increase the memory, if you are not satisfied with the modification, it is easy to undo it.
Unfortunately, refactoring cannot rename the text in the comment. Therefore, annotations in the class, file header comments generated by xcode, or any document comments you write must be edited manually. You can use the search and replacement functions to simplify this process.
Code navigation
The lifecycle of most source files is similar. After being created, a large amount of code is written to implement various functions. Next, you enter the stage of addition, modification, and maintenance. You must read a large number of files before you can add or modify code. Finally, when writing a class, you need to browse its code before the application to understand how it works. This section describes how to browse code in the Code lifecycle.
1. emacs
Emacs is a long-known text editor. It was born in 1970s and can run on a modern Mac operating system. Here we will briefly introduce some of its shortcut key combinations and their meanings.
This is a shortcut that allows you to move the cursor in text without having to remove the mouse from the keyboard. These shortcut keys can be used in various software under MAC.
Control-F: move the cursor one cell
Control-B: move the cursor behind a grid
Control-P: move the cursor up a row
Control-N: move the cursor down a row
Control-A: move the cursor to the section header
Control-E: move the cursor to the end of the paragraph
Control-T: swap the characters on both sides of the cursor
Control-D: Delete the character on the right of the cursor
Control-K: deletes all characters after the cursor of the current row, so that you can easily rewrite the code at the end of the line.
Control-L: place the cursor in the center of the window. If you cannot find the cursor position or want to move the window to quickly locate the cursor in the center, this shortcut is very useful.
2. Quick Start tips
If you see the # Import Statement at the top of a file when browsing a source file, you only need to select the file name (or even do not need to select it. h), and then select the File Open quickly option. xcode will open this header file for you.
If you do not select any text, selecting the Open quickly option opens a dialog box, which is another file search method, you can also use the shortcut key command + Shift + D to execute the Open quickly command. This dialog box is a very simple window with only one search domain and one table, but it is a very quick search method for project content.
If your monitor is large, you can use the help window (view assistant editor) next to the main editor ). By default, if one panel displays a header file, the other panel displays an implementation file. However, you can change this setting based on your preferences. Click counterparts in the toolbar to view other options.

Concentrate on
You may have noticed two blank columns next to the left of the source code. The wide column on the left is called the sidebar. We will talk about it later when discussing debugging. The narrow column is called the focus column, which allows you to focus on a part of the code.
Pay attention to the gray level of the Focus column. The deeper the code is nested, the deeper the gray level in the focus column next to it. This color encoding makes the complex code programs clear at a glance. You can hover your mouse over different gray areas of the Focus bar to highlight the corresponding code snippet.
You can also click the focus column to collapse the corresponding code snippet.
Use navigation bar
There is a widget bar at the top of the Code Editor, that is, the navigation bar. Many of the preceding controls allow you to quickly switch between source files in the project.
The leftmost menu button of the navigation bar allows you to quickly open history files recently accessed by the editor or perform other advanced operations. The "back" and "Forward" buttons can be used to open the edited files. They work in the same way as the "back" and "Forward" buttons in safari. The two buttons are followed by the path of the current file in the project (not only the directory path ). Each item in the path is a button. You can click any of them and navigate to the file in the pop-up menu.
The last item is the function menu, which displays all functions and methods in the current class. If you press and hold the command button and click the function menu, you can sort these methods alphabetically.
In addition to the method name, you can add other content to the menu. There are two methods: Use # pragma mark whatever. You can enter any text in whatever and it will appear in the function menu. For example, # pragma mark-inserts a split line in the menu. The other is to use "// MARK:", "// todo:", "// fixme:", "//! : "," //? : "And other text comments starting with a symbol, and put the text into the function menu. These are all the marks made by the program; it is best to look at these marks before the program is released. (Speak silently: test, in 4.6.2 //!!! : It will not be displayed in the function menu. I don't know if I didn't write it correctly or if I didn't say it in the book, or because the comment was canceled after the version upgrade .)
"Pragma" originated from Greek, meaning "action ". # The Pragma command passes information or instructions beyond the general code of objective-C to the compiler and code editor. Generally, Pragma is ignored, but it may have other meanings in some software development tools. For example, you can use it to mark unfinished work so that you can continue the unfinished work the next day, or write down the items that should be noted but easily forgotten in the program. If a tool does not know what Pragma is, it does not generate a warning or error message. Instead, it is very intelligent to ignore it.

Obtain information
Switching between code and cocoa header files is a good function and convenient, but sometimes you need to obtain information from outside the code. Fortunately, xcode has a "treasure" for storing documents and reference materials ".
1. Get help
There are two icons at the top of the checker. Currently, the first icon is selected, and the checker displays various attributes of the current file. Another icon can enable the quick help feature in the checker. If you want quick help, click any location in the Code and observe the content in the checker. If you click another location in the source code, the quick help panel will be updated.
2. Document Management Program
If you want to directly access Apple's official API documentation, the quickest way is to press and hold the option key and double-click a symbol, which is a shortcut for searching the documentation related to the symbol.
Debugging
Bugs are everywhere, and errors in programs are inevitable, especially when you start using new platforms and languages. After discovering the problem, take a deep breath, take a sip of your favorite drink, and then systematically find out the cause of the error. This process is called debugging ).
Brute force testing
Write the output statement in the program to output the program's control flow and some data values. You may have been doing this all the time, but you do not know that this debugging method is called brute force testing. (Silent Voice: indeed, it is the first time that we have heard of this most common and effective method, called brute force testing, for so many years .... It's no wonder that urban management like it so much ....)
Xcode Debugger
A debugger is a program between your program and the operating system. It can interrupt the program, so that you can check the program data and even modify the program. After completing these steps, you can restore the program and view the running results. You can also execute the code in one step to speed up the program running, and carefully check the changes made to the data in the code.
Xcode also provides a debugging window that provides a large amount of summary information and a debugging console that can directly send Debugging commands to the debugger.

Exquisite debugging symbols
When you plan to debug the program, make sure that you are using debug to build the configuration. You can find it in the edit scheme drop-down menu in the xcode toolbar. The build configuration notifies the compiler of additional debugging symbols through which the debugger can know where they are in the program.
Start debugging
The first thing to debug is to set a breakpoint. Just like the vast majority of Ides, you can click a line number to see a blue arrow, which is the new breakpoint. Deleting a breakpoint is odd. You can drag the blue arrow out of the row number column with a small explosion animation. If you click the blue arrow again, the Blue Arrow becomes lighter, indicating that it is temporarily disabled.
After the breakpoint is set, click Run. If the program passes the breakpoint, it stops at the breakpoint. At this time, you will see an extra control bar above the debugger panel.
From the left, the first button is used to open or close the debugger pane. The following four buttons control the next behavior of the program. The first button is like the playback button of the player. After you click it, the program continues to run until the next breakpoint ends or crashes.
The next button is the one-step skip button, which looks like an arrow jumping over a small obstacle. Click it to execute a line of code, and then stop and wait for your command. The next button is a single-step button, which looks like a downward arrow pointing to a small black spot. Click it and it will let the code enter a method or function (if the program contains the source code of the function or method with the current cursor, if you do not have the source code, it serves the same purpose as skip a single step ).
Click the last button to jump out and click it to directly execute the currently running function. The program stops in the next row of the called function.
The following control is a drop-down menu that allows you to choose which thread to observe.
On the right side of all buttons is the call stack, which displays a set of currently active functions.
Check Program
Now that the program is stopped, what should I do next? Generally, when you set a breakpoint or one-step execution in a certain part of the program, it means you want to know the program status-variable value.
Xcode has the data prompt function. You can hover your mouse over a variable or method parameter. xcode will pop up a small window to display its value.
Memo table
This chapter introduces many shortcut keys and draws a table Summary:
Button description
Command + [move code block left
Command +] Right Shift code block
The tab key is prompted to automatically complete the code.
ESC key display code prompt menu
Control +. (half-width period) Circular browsing code prompt
Shift + Control +. (full stop) reverse loop browsing code prompt
Command + Control + S create Snapshot
Control + F forward cursor
Control + B move the cursor behind
Control + P move cursor to previous line
Control + n move cursor to next line
Control + a move the cursor to the beginning of the line
Control + e move the cursor to the end of the row
Control + t exchange the characters on both sides of the cursor
Control + D Delete characters on the right of the cursor
Control + k Delete row
Control + l place the cursor in the center of the window
Command + Shift + O show open quickly window
Command + Control + up arrow key to open the corresponding file
Press and hold the option key and double-click the mouse to search for the document.
Command + y enable/disable breakpoint
Command + Control + y continue to run (effective in the debugger)
F6 skip
F7 jump
F8 jump out
                                                                                                                                                                                                                                                                                             

Summary
This chapter introduces some basic features and usage of xcode, especially shortcut keys, which can improve our work efficiency.
The following sections detail some classes in cocoa. The interesting "class" is coming!

Related Article

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.