Summary of iOS development debugging tips (ongoing update)

Source: Internet
Author: User

The snowy text of Kilimanjaro

For software development, debugging is the skill that must be learned, and the importance is self-evident. For debugging skills, basically can be migrated, that is, you previously mastered on other platforms a lot of debugging skills, many can also be used in iOS development. Different languages, different Ides, different platforms for debugging, there are same-sex and personality. Today we will learn the debugging skills in iOS development, language take up for oc,ide of course is a powerful xcode. First of all, Xcode has provided great convenience for our commissioning project.

"1. Normal breakpoint"

Breakpoints (breakpoint) are definitely the first choice for debugging programs and are the basic skills to master. As the name implies, when the program runs to a breakpoint, it pauses to run. For example, the breakpoint hit 11 lines, then the program will stop at 11 lines (Note: The program only runs to the first 10 lines, the 11th line is not actually executed!!!) )。 Just click Next to the line of code to add a breakpoint and click again to make the breakpoint unusable (disable, still exists, just doesn't work). The shortcut key for creating a breakpoint on a line is: command+\

And you can see the values of the parameters below during the debugging process:

"2. Conditional breakpoint"

The breakpoint above is only the most common, we can also configure the properties of the breakpoint, set conditions, make the breakpoint more intelligent, right-click the breakpoint into the Edit dialog box:

I use a loop as the test code:

The code in the loop is executed one step at a time, which may not be what I want. I want to interrupt the program at the time I is 3, debug it, write the conditions as follows:

When you set a condition for i==3, the program breaks when that condition occurs, not every time you arrive at that location. The output of the interrupt is as follows:

You can also set the Ignore parameter, ignoring the first n times of the breakpoint run, will be interrupted n+1.

The debug output is as follows:

Also, you can see how many times a function has been called, set the action parameter as follows, and note that you want to select automatically continue after evaluating actions.

The output results are as follows:

"3. Exception Breakpoint"

The function of a breakpoint is not limited to the above mentioned. Development iOS knows that if we crash the program because of the exception, the code goes directly to MAIN.M's main function. Why can't you just run into the code where the exception occurred??? The exception breakpoint solves the problem for us, and the program terminates at the line where the exception occurred. The Create exception breakpoint legend is as follows:

The creation is complete as shown below. If you encounter an exception crash, try using an exception breakpoint.

"4. Symbol Breakpoint Symbolic Breakpoint"

The creation of a symbolic breakpoint is also the same as an exception breakpoint. A generic symbolic breakpoint can break execution when you specify a [class name method name].

Configure the symbol breakpoint as follows: You can break execution when you execute the Viewdidload method to the Viewcontroller class.

If your symbol only writes a function name, it will break execution where the function name appears. As below, it will be interrupted when running to doanimation. Isn't it strong?

"5.Analyze Analyzer"

The Analyze parser is a static tool that can analyze our programs to find out what variables we haven't used, or some dead storage. The execution Analyze is as follows: Product-->analyze. The following blue marks are the result of static analysis.

Of course, we can set the analyze when compiling the program, and set the following options to Yes.

"6.Profile Inspector"

This tool is really too NB, few words said, paste a picture, we feel, I will be in the future blog slowly explain the use of the tool. Also open in Product-->profile.

"7. Zombie Object"

An exception will occur in iOS where objects that have been released but not completely disappear are called Zombie objects and are freed again for objects that have already been release. Although since the use of arc, the exception caused by object release has been greatly reduced, but occasionally occurs. When you turn on Zombie object mode, you can quickly navigate to the exception location. The opening method is as follows: Product-->scheme-->edit Scheme. Tick enable Zombie objects.

"8.lldb Command"

Xcode uses the LLVM compiler, which is recognized as the best C, C + +, OC, and Swift compilers. While Lldb is the debugger in LLVM, we can use some simple commands to debug, I still put the loop code above as the test code.

In breakpoint debugging, use the PO command, the Print command, to print the variable information in the console console:

"9.NSLog Printing"

It should be said that NSLog printing information is a beginner's favorite debugging techniques, but also the simplest debugging, through the printed information to see the path of the program run. But print out less information, itself nslog efficiency is low, some people use the macro to do a partial optimization, the code is as follows: Can print out the class name, the method name, detail time, line number.

12345678910111213141516171819202122232425 #import "ViewController.h"    #define NSLog(format, ...) do { \  fprintf(stderr, " %s\n", \  [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], \  __LINE__, __func__); \  (NSLog)((format), ##__VA_ARGS__); \  fprintf(stderr, "-------\n"); \  while(0)    @interface ViewController ()   @end    @implementation ViewController    - (void)viewDidLoad {        [superviewDidLoad];      for(int i = 0; i < 5; i++) {          NSLog(@"我的值:%d",i);      }  }    @end

The printing results are as follows:

"10. Life cycle Method Init,dealloc"

For Viewcontroller, there are two life cycle functions that we can rewrite, that is, the Init and Dealloc methods. For the state of some objects, we can view them in both methods. Especially in Dealloc, you can see whether an object is release when Viewcontroller exits.

12345678910111213 - (instancetype)init  {      self = [super init];      if(self) {          //初始化语句;      }      returnself;  }    - (void)dealloc  {      //释放后调用;  }

"11. View Code Uptime"

Sometimes we want to know exactly what a piece of code is, the time it takes to execute it, and then analyze the efficiency and so on, and how much time it will take to execute. Just to see someone on the internet has done this job, I took it off directly. It is also possible to calculate time in a macro way, as long as we write the Tick,tock macro before and after the code block that needs to calculate the time. Of course, the principle is also very simple, that is, using nsdate to calculate the difference.

1234567891011121314151617181920212223 #import "ViewController.h"    #define TICK   NSDate *startTime = [NSDate date]  #define TOCK   NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])    @interface ViewController ()    @end    @implementation ViewController    - (void)viewDidLoad {        [superviewDidLoad];        TICK;      for(int i = 0; i < 5; i++) {          NSLog(@"我的值:%d",i);      }      TOCK;  }    @end

The printing results are as follows:

"12. Mobile phone screenshot"

Mobile phone screenshots also calculate debugging? Ha ha. In fact, is a development of a small skill ha. In fact, we will be on the iphone at the same time press the power button +home key screen, and then use a variety of communication software to send to others, this is slightly inconvenient. Let's take a screenshot using the way in Xcode. When the phone is connected to the computer, be careful to select the commissioning device as your own mobile phone:

Then choose Debug-->view Debugging-->take screenshot .... You can then see that the phone screen is already on your computer's desktop. Is it more convenient to operate directly on the phone? This can be quickly sent to other developers, PM and other people.

"13.viewDidLoad does not recommend writing too much code"

Personal suggestions do not write too much code in the Viewdidload method. Especially when it comes to animations in this interface, the interface may not be fully loaded when the Viewdidload method is executed, and if you put the animation in Viewdidload at this point, it may cause the animation to fail to display. Of course, it is not recommended to put the time-consuming network requests and animation effects in the Viewdidload, the interface blocking will also cause the animation can not be displayed. You can try to put the animation in the Viewdidappear,viewwillappear method. For this kind of UI-related problems, debugging is also more troublesome ...

"14. View Debugging"

There are many ways in which iOS has developed a UI design, such as Storyboard,xib and code implementations. For the Stoayboard,xib visualization implementation is relatively simple, but for some "old iOS programmers," like to use code to implement the UI, and perhaps the UI hierarchy is more complex. This will bring a lot of trouble to the developers of our new project. The quickest way to quickly see the interface hierarchy and layout of a complex UI is to use view debugging.

When the project runs to an interface (which can be an emulator or a real machine), turn on view debugging, click the button

This will enter the attempt to debug, you can easily view the interface. Here you can see the hierarchical relationship between controls.

The tree-level diagram on the left lets you switch between viewing threads, queues, and UI:

"15" common compilation macro definition: Allows code to be executed under different compilation conditions.

(1) __optimize__: Used for release and debug judgment, when the __optimize__ is selected, you can let the code at release time to execute, at debug do not execute. Examples are as follows:

12345 #ifndef __OPTIMIZE__      //这里执行的是debug模式下  else    //这里执行的是release模式下  #endif

(2) __i386__ and __x86_64__: The judgment of the simulator environment and the real machine environment. The code that satisfies the condition is executed only under the emulator. The sample code is as follows:

1234567 #if defined (__i386__) || defined (__x86_64__)        //模拟器下执行  #else        //真机下执行  #endif

(3) __iphone_os_version_max_allowed: The currently compiled SDK version, can be compared with macro definitions such as __IPHONE_9_0, to perform different versions of the code. Examples are as follows:

12345 if(__IPHONE_OS_VERSION_MAX_ALLOWED == __IPHONE_9_0) {          //如果当前SDK版本为9.0是执行这里的代码      }else{          //否则执行这里      }

The "16" precompiled macro #ifdef #else #endif

12345 #ifdef ****      //代码1  else    //代码2  #endif

This means that if the identifier has been defined by the # define command, code 1 is compiled, or code 2 is compiled.

There are also #ifndef, which is the opposite of #ifdef.

Summarize

Debugging is not only the skills I mentioned above, more is the experience accumulated over the years, only in their own development of continuous error, trial and error, wrong adjustment, the process of solving errors can improve their programming level and debugging ability. I will continue to update this blog to explain more debugging skills, I hope we can improve in practice.

Summary of iOS development debugging tips (ongoing update)

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.